Gibbs
Gibbs

Reputation: 22956

Java - Pattern matching between the same pattern

My sample string:

 a ghgduysgd a fdferfdf a bvfxbgdf a gdfgdfg

I need to find all the contents between a's.

I have (?<=a).* But it matches all the contents after a. But I want to find between a.

First iteration: ghgduysgd

Second iteration: fdferfdf

I want to get data like the above for the manipulation. can you help with regex?

Upvotes: 0

Views: 63

Answers (3)

TheLostMind
TheLostMind

Reputation: 36304

You can try regex like this (and ignore the first value)

String path = "a ghgduysgd a fdferfdf a bvfxbgdf a gdfgdfg";
String[] arr = path.split("(\\s+)?a(\\s+|$)"); // split based on a preceeded and followed by space
for (String s : arr) {
    System.out.println(s);
}

O/P :

// Empty String here. Since your String starts with a
ghgduysgd
fdferfdf
bvfxbgdf
gdfgdfg

Upvotes: 5

Ioanna Katsanou
Ioanna Katsanou

Reputation: 504

You could split the String where there is an "a" and then trim the spaces and save it in an ArrayList. Then if you want to print the whole word you could use Stringbuilder to concatenate the Strings.

   String word="a ghgduysgd a fdferfdf a bvfxbgdf a gdfgdfg";
        List<String> list=new ArrayList<String>();
        list= Arrays.asList(word.split("a")); 
        StringBuilder sb = new StringBuilder();
        for(String item: list){
            item.trim();
        System.out.println(item);
        sb.append(item);
        }

        System.out.println(sb);

Upvotes: 1

f1sh
f1sh

Reputation: 11934

You alrady use a lookbehind in your regex, change it to also use a lookahead:

(?<=a).*(?=a|$)

Then make the .* non-greedy to stop at the first available "ending" a:

(?<=a).*?(?=a|$)

EDIT: the a|$ is from tobias_k's comment below, originally it was just a

Upvotes: 1

Related Questions