Need help with using regular expression in Java
I am trying to match pattern like '@(a-zA-Z0-9)+ " but not like 'abc@test'.
So this is what I tried:
Pattern MY_PATTERN
= Pattern.compile("\\s@(\\w)+\\s?");
String data = "abc@gere.com #gogasig @jytaz @tibuage";
Matcher m = MY_PATTERN.matcher(data);
StringBuffer sb = new StringBuffer();
boolean result = m.find();
while(result) {
System.out.println (" group " + m.group());
result = m.find();
}
But I can only see '@jytaz', but not @tibuage. How can 开发者_运维百科I fix my problem? Thank you.
This pattern should work: \B(@\w+)
The \B
scans for non-word boundary in the front. The \w+
already excludes the trailing space. Further I've also shifted the parentheses so that the @
and +
comes in the correct group. You should preferably use m.group(1)
to get it.
Here's the rewrite:
Pattern pattern = Pattern.compile("\\B(@\\w+)");
String data = "abc@gere.com #gogasig @jytaz @tibuage";
Matcher m = pattern.matcher(data);
while (m.find()) {
System.out.println(" group " + m.group(1));
}
精彩评论