richard
richard

Reputation: 14751

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 = "[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.

Upvotes: 1

Views: 99

Answers (1)

BalusC
BalusC

Reputation: 1108642

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));
}

Upvotes: 3

Related Questions