Reputation: 1007
How to macth a backslah (\) in java regular expression? I hava some sript to matching all latex tag In some file but it didnt work.
public class TestMatchTag {
public static void main(String[] args) {
String tag = "\begin";
if (Pattern.matches("\\\\[a-z]+", tag)) {
System.out.println("MATCH");
}
}
}
Upvotes: 2
Views: 3549
Reputation: 387
This should work...
Pattern.matches("\\[a-z]+", tag);
[a-z] allows any character between a-z more than once and \\ allows "\" once.
you can validate your expression online here
Upvotes: -1
Reputation: 1153
You need another backslash to escape the "\" in "\begin", change it to "\begin", otherwise the "\b" in your "\begin" will be considered as one character.
Upvotes: 0
Reputation: 8395
Replace String tag = "\begin";
with String tag = "\\begin";
. The regex is valid, but your input string needs to escape \
character.
Upvotes: 2