tags:

views:

52

answers:

1

Hi,

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 = "[email protected] #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.

+3  A: 

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 = "[email protected] #gogasig @jytaz @tibuage";
Matcher m = pattern.matcher(data);
while (m.find()) {
    System.out.println(" group " + m.group(1));
}
BalusC