1

I am having trouble with Java Pattern and Matcher. I've included a very simplified example of what I'm trying to do.

I had expected the pattern ".\b" to find the last character of the first word (or "4" in the example), but as I step through the code, m.find() always returns false. What am I missing here?

Why does the following Java code always print out "Not Found"?

                Pattern p = Pattern.compile(".\b");
                Matcher m = p.matcher("102939384 is a word");
                int ixEndWord = 0;
                if (m.find()) {
                    ixEndWord = m.end();
                    System.out.println("Found: " + ixEndWord);
                } else {
                    System.out.println("Not Found");
                }
Jeremy Goodell
  • 18,225
  • 5
  • 35
  • 52

2 Answers2

3

You need to escape special characters in the regex: ".\\b"

Basically, in a String the backslash has to be escaped. So "\\" becomes the character '\'.

So the String ".\\b" becomes the litteral String ".\b", which will be used by the Pattern.

AntonH
  • 6,359
  • 2
  • 30
  • 40
0

To expand upton AntonH's comment, whenever you want the "\" character to appear in a regex expression, you have to escape it so that it first appears in the string you are passing in.

As is, ".\b" is the string of a dot . followed by the special backspace character represented by \b, compared to ".\\b", which is the regex .\b.

Mshnik
  • 7,032
  • 1
  • 25
  • 38
  • Hang on, is it a dot, or the regex dot representing any character? – Jeremy Goodell Oct 08 '14 at 20:49
  • 1
    just a dot will match any character, as expected: http://stackoverflow.com/questions/1480284/java-regular-expression-value-split-the-back-slash-dot-divides-by-char – Mshnik Oct 08 '14 at 20:50