Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with Java Regex \b

Tags:

java

regex

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?

like image 441
Anton Avatar asked Jan 08 '12 13:01

Anton


People also ask

What does \b mean in regex Java?

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

Is Java regex pattern thread safe?

Instances of this (Pattern) class are immutable and are safe for use by multiple concurrent threads. Instances of the Matcher class are not safe for such use.

What is the meaning of \\ s+ in Java?

The Difference Between \s and \s+ For example, expression X+ matches one or more X characters. Therefore, the regular expression \s matches a single whitespace character, while \s+ will match one or more whitespace characters.

What is the use of \\ in Java?

The backslash \ is an escape character in Java Strings. That means backslash has a predefined meaning in Java. You have to use double backslash \\ to define a single backslash. If you want to define \w , then you must be using \\w in your regex.


1 Answers

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).

like image 152
Bohemian Avatar answered Oct 16 '22 16:10

Bohemian