Reputation: 43
I cant understand why the result is always false
package test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String args[]) {
String pattern = "place (//d+);(//d+);(//d+);(//d+)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
Matcher matcher1 = r.matcher("place 66;33;65;87");
System.out.println(matcher1.matches());
}
}
Upvotes: 0
Views: 258
Reputation: 44992
The escaping character in both regex and java String literals is a backslash, not a forward slash. You want to get \d
in regex (escaped d
for digits). You have to escape it by another backslash in string literal, so you obtain \\d
.
With
"place (\\d+);(\\d+);(\\d+);(\\d+)"
it matches and works.
You can of course take it sportive and try to write a regex-replacement that replaces all //
by \
in your regex... Something like this:
String pattern = "place (//d+);(//d+);(//d+);(//d+)".replaceAll("//", "\\\\");
Upvotes: 1
Reputation: 2082
This would work:
public static void main(String args[]) {
String pattern = "(place) (\\d+);(\\d+);(\\d+);(\\d+)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
Matcher matcher1 = r.matcher("place 66;33;65;87");
System.out.println(matcher1.matches());
}
You need to provide place
in round braces and the slash thing.
Upvotes: 0