Reputation: 21405
I am writing a simple regular expression program using the expression:
uid=swg2*([C]?[1247]\d{6})
Initially I tried to get a valid input string for this expression using the online regex tool and got a valid example string as uid=swg2C1\dddddd
.
I also tried with uid=swg2C1\\123456
in my Java program but getting same issue.
Now if I use this in my Java program then it is not working as expected:
public static void main(String[] args) {
String input = "uid=swg2C1\\dddddd"; // Tried with "uid=swg2C1\\123456", same issue
if (Pattern.compile("uid=swg2*([C]?[1247]\\d{6})").matcher(input).find()) {
System.out.println("valid input");
} else {
System.out.println("invalid input");
}
}
If I run this program I am getting message as invalid input. But my string is valid input as per the online tool. Please help me what is wrong with my input data.
Upvotes: 0
Views: 201
Reputation: 271460
You did not escape your backslashes!
uid=swg2*([C]?[1247]\\d{6})
^^
These should be escaped!
In Java code, if you did not escape them, the two backslashes in Java code will become one \
in regex. This means that the engine will treat the string like this:
uid=swg2*([C]?[1247]\d{6})
\d
means digits, so the engine thinks you are trying to match 6 digits!
So, remember to escape them by adding one more \
before each \
:
"uid=swg2*([C]?[1247]\\\\d{6})"
Upvotes: 2