finding matches inside pipes using java regexp

∥☆過路亽.° 提交于 2019-12-24 11:04:55

问题


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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/8178539/finding-matches-inside-pipes-using-java-regexp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!