Home > OS >  java.util.regex matching parentheses
java.util.regex matching parentheses

Time:05-27

I am using java.util.regex for matching like bellow

public static void main(String[] args) {

    String input = "<b>I love you (LT): </b>xxxxxxxxxxxxxxxxxxxxxxxxx";

    String patternStr =  "I love you (LT):";
    String noParentStr =  "I love you";

    Pattern pattern = Pattern.compile(patternStr);
    Pattern noParentPattern =  Pattern.compile(noParentStr);

    Matcher matcher = pattern.matcher(input);
    Matcher noParrentTheseMatcher = noParentPattern.matcher(input);

    System.out.println("result:"   matcher.find());
    System.out.println("result no parenthese:"   noParrentTheseMatcher.find());
}

I can see the input string contain patternStr "I love you (LT):". But i get result

result:false
result no parenthese:true

How can i match string contain parentheses '(',')'

CodePudding user response:

In regex, parentheses are meta characters. i.e., they are reserved for special use. Specifically a feature called "Capture Groups".

Try escaping them with a \ before each bracket

I love you \(LT\):

List of all special characters that need to be escaped in a regex

CodePudding user response:

As it has been pointed out in the comments, you don't need to use a regex to check if your input String contains I love you (LT):. In fact, there is no actual pattern to represent, only a character by character comparison between a portion of your input and the string you're looking for.

To achieve what you want, you could use the contains method of the String class, which suits perfectly your needs.

String input = "<b>I love you (LT): </b>xxxxxxxxxxxxxxxxxxxxxxxxx";
String strToLookFor = "I love you (LT):";
System.out.println("Result w Contains: "   input.contains(strToLookFor));  //Returns true

Instead, if you actually need to use a regex because it is a requirement. Then, as @Yarin already said, you need to escape the parenthesis since those are characters with a special meaning. They're in fact employed for capturing groups.

String input = "<b>I love you (LT): </b>xxxxxxxxxxxxxxxxxxxxxxxxx";
String strToLookFor = "I love you (LT):";

Pattern pattern = Pattern.compile(strPattern);
Matcher matcher = pattern.matcher(input);

System.out.println("Result w Pattern: "   matcher.find());  //Returns true
  • Related