Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression is not working with single character

Tags:

java

regex

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)

like image 840
MLS Avatar asked Sep 11 '18 05:09

MLS


People also ask

How do you match a single character with a regular expression?

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.

Which represents a single character in a regular expression?

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.

Which character does does not match in single line mode of regex?

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 .


1 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.

like image 184
blhsing Avatar answered Sep 30 '22 21:09

blhsing