chip
chip

Reputation: 3279

finding matches inside pipes using java regexp

how do you get the contents of the string inside the pipe?

|qwe|asd|zxc|

how can I get

qwe asd zxc

i tried this

"\\|{1,}(\\w*)\\|{1,}"

and it don't seem to work

i also tried this

"\\|{1,}[\\w*]\\|{1,}"

it only returns qwe though

Upvotes: 1

Views: 350

Answers (2)

fardjad
fardjad

Reputation: 20394

Regex is not needed for this but if you insist on using regexes:

Pattern p = Pattern.compile("\\|?(\\w+)\\|");
Matcher m = p.matcher("|qwe|asd|zxc|");
while (m.find()) {
    System.out.println(m.group(1));
}

/* outputs:
qwe
asd
zxc 
*/

Why your regex doesn't work:

/\|{1,}(\w*)\|{1,}/ is similar to /\|(\w*)\|/ and it matches the words between pipes.

Now in your sample string, the first match is |qwe|.

Then it continues finding matches in asd|zxc|; according to the pattern it skips asd and only matches |zxc|.

You can fix this by making the preceding pipe optional.

Upvotes: 1

Sumit Singh
Sumit Singh

Reputation: 15886

if String line="|qwe|asd|zxc|"; then
use string[] fields = line.split("\\|");
to get array of all your result..

Upvotes: 0

Related Questions