0

I am trying to match a pattern like so:

TR @(any number of word characters go here):

So the pattern begins with TR then has one space then has @ and then has any characters and terminates with a :

Here is my regex: Pattern p = Pattern.compile("TR\\s@[\\w]+:");

It is working and for example will fail on:

TR @abcnews:

I think my error is with the whitespace.

3
  • 1
    This is certainly not the source of the mistake, but the [] around \\w are redundant. Commented Oct 30, 2012 at 23:13
  • 1
    Your regex matches your example string just fine. What is your problem? Commented Oct 30, 2012 at 23:15
  • Your regex also doesn't do exactly what you describe: it won't just match a single space after 'TR', but any whitespace character (space, tab, return, line feed, form feed, or vertical tab). You can use a literal space (' ') if you actually need a space. Commented Oct 31, 2012 at 0:03

1 Answer 1

1

DEMO

Regex: TR\s+@(\w+):

This even backreferences the text, it accepts multiple spaces between the TR and @ so it would work pretty well for you, sir.

EDIT A java code that it's properly working:

Matcher ma = Pattern.compile("TR\\s+@(\\w+):").matcher("TR    @asdfasd:");
while (ma.find()) {
    System.out.println(ma.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.