14

I tried \b (This means the last character of a word) in the Java Regexp, but this doesn't work.

String input = "aaa aaa";
Pattern pattern = Pattern.compile("(a\b)");
Matcher matcher = pattern.matcher(input);

while (matcher.find()) {
    System.out.println("Found this wiki word: " + matcher.group());
}

What in the problem?

2
  • 6
    Note: \b does not mean "last character of a word" but "boundary between word and non-word". Commented Jan 8, 2012 at 13:40
  • 1
    I'm not sure what you want to do, even with the regex corrected ("a\\b", and see other comments about \b), your groups will always contain a only. So, what is it you want to do? Commented Jan 8, 2012 at 13:57

2 Answers 2

26

In Java, "\b" is a back-space character (char 0x08), which when used in a regex will match a back-space literal.

You want the regex a\b, which in java is coded by escaping the back-slash, like this:

"a\\b"

btw, you are only partially correct about the meaning of regex \b - it actually means "word boundary" (either the start or end of a word).

Sign up to request clarification or add additional context in comments.

1 Comment

And it might fail on non-ASCII words (unless you're using JDK 7) where \b matches in unexpected places (visualized by |: Ü|bertr|ä|ger|).
5

Literal backslashes in Java strings need escaping, so the regex \b becomes "\\b" as a Java string.

6 Comments

Huh... what? Regex = regular expression.
Both \` and \b` are escape sequence (character) in Java.
I'm just indicating that the term you're using is incorrect.
I'm telling nowhere \b is regex. Stop the useless comments.
Huh? Where's \b there? I'm not answering further in this useless discussion.
|

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.