问题
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