I am trying to write regular expression in Java
to evaluate two strings mentioned with () separated by ,
Example: (test1,test2)
I have written below code
public static void main(String[] a){
String pattern = "\\([a-zA-Z0-9]+,[a-zA-Z0-9]+.\\)";
String test = "(test1,test2)";
System.out.println(test.matches(pattern));
}
It works as expected and prints true
in below cases
String test = "(test1,test2)";
String test = "(t,test2)";
But it is printing false
when I send below
String test = "(test1,t)";
It is strange because I am using same expression before and after ,
It returns true
for (t,test2)
but not for (test1,t)
Please let me know what am I missing in this regular expression. I need it to evaluate and return true
for (test1,t)
Match any specific character in a setUse square brackets [] to match any characters in a set. Use \w to match any single alphanumeric character: 0-9 , a-z , A-Z , and _ (underscore). Use \d to match any single digit. Use \s to match any single whitespace character.
A dot character matches any single character of the input line. The ¬ character does not match any character but represents the beginning of the input line. For example, ¬A is a regular expression matching the letter A at the beginning of a line.
Single-line mode language element so that it matches every character, instead of matching every character except for the newline character \n or \u000A . The $ language element will match the end of the string or a trailing newline character \n .
There's no need for the .
(that matches one character) in your regex. Remove .
from your regex so it becomes "\\([a-zA-Z0-9]+,[a-zA-Z0-9]+\\)"
and it should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With