1

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.

1 Answer 1

3

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));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.