Problem specifying \ in a string literal Using Matcher/Patteren class's
Hi , I have created a simple program below to test how java handles regular expressions , I have created a pattern object p specifying an array of characters as the parameters, then created the Matcher object m using p as the pattern and a string of characters as the parameter then invoked the matches()on the matcher object m and printed the boolean result to the console.
Code Java:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class regexTest {
public static void main (String []args) {
Pattern p = Pattern.compile("[a-zA-Z0-9-
/]+");
Matcher m = p.matcher("123456-07//");
boolean b = m.matches();
String s1 = m.toString();
System.out.println(m.matches());
System.out.print(m.toString());
}
}
The program works fine and returns a Boolean true to the console indicating the match was successful for the following
Pattern p = Pattern.compile("[a-zA-Z0-9-
/]+");
Matcher m = p.matcher("123456-07//");
Result = true
java.util.regex.Matcher[pattern=[a-zA-Z0-9-\/]+ region=0,11 lastmatch=123456-07//]<<< Process finished.
The problem occurs when I want to add the \ character to the pattern and matcher class character sequence.
Note: As backslashes within string literals in java are interpreted as character escapes its necessary to use double backslash
to represent a single backslash, thus the expression
matches a single backslash.
Adding
to both Pattern and Matcher :
Pattern p = Pattern.compile("[a-zA-Z0-9-
/]+");
Matcher m = p.matcher("123456-07
//");
Result = false
java.util.regex.Matcher[pattern=[a-zA-Z0-9-\/]+ region=0,12 lastmatch=]<<< Process finished.
As Can be seen the Result retuned is false and there is no match
How can I specify the \ character in the pattern and matcher in order to have a Boolean True returned??
I have tried using a single character \ in the Matcher but the compiler does not like it.
egexTest.java:9: illegal escape character
Matcher m = p.matcher("123456-07\//"
Any Help or direction on this simple but highly frustrating problem greatly appreciated.
Thanks in advance
Re: Problem specifying \ in a string literal Using Matcher/Patteren class's
I think you're confusing backward and forward slashes. Can you throw together another example with only the String and pattern you're trying to match against? It might seem obvious to you, but I'm not sure which of those lines you're attempting to use.