Regular expression is not working with single character

Viewed 807

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)

7 Answers

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.

Use this regex:

String pattern = "^\\(.+,.+\\)";

This will match your required strings.

In the second part of your pattern, you have "[a-zA-Z0-9]+."

If you're trying to match "t", it will see t for the [a-zA-Z0-9]+ part, but it requires another character after that to match the . part.

Revised pattern: "\\([a-zA-Z0-9]+,[a-zA-Z0-9]+\\)"

Delete the dot after the second group[a-zA-Z0-9]

Demo

and even simpler you can use \w for words, you can use instead of [a-zA-Z0-9]

so your regular expression would be like that

\(\w+,\w+\)

In your regular expression '.' is not needed in the latter part. change is as "\([a-zA-Z0-9]+,[a-zA-Z0-9]+\)" so that it will be returning true for "(test,t)"

String pattern = "\\([a-zA-Z0-9]+,[a-zA-Z0-9]+\\)";
String test = "(te,t)";
System.out.println(test.matches(pattern)); // true
String pattern = "\\([a-zA-Z0-9]+,[a-zA-Z0-9]+\\)";
String test = "(test1,test2)";
String t1 = "(t,test2)";
String t2="(test2,t)";
System.out.println(test.matches(pattern));
System.out.println(t1.matches(pattern));
System.out.println(t2.matches(pattern));

just try this code, it will give you answer you want.

You have written "." at the end after + in your pattern so clear it.

Related