简体   繁体   中英

java.util.regex matching parentheses

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 the result

result:false
result no parenthese:true

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

In regex, parentheses are meta characters. ie, 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM