-1

I wrote a Java program to find the pattern "Type": "Value" in a string.This is the pattern i wrote -> "Type[\W]*Value" . "Value" is replaced with actual value at run time It works for strings like "Type":"Name" or "Type":"Name<" but when i pass parenthesis, it fails.

"Type":"Name(" - java.util.regex.PatternSyntaxException: Unclosed group near inex.

"Type":"Name()" - No match found.

I don't have much experience writing regular expression. Can someone please help me in understanding the issue.

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;

public class PatternFinder {
    public static void main(String args[]) {
        System.out.println(findPattern("Name","abcd7<","{\"response\":{\"Name\":\"abcd7<\"}}"));
        System.out.println(findPattern("Name","abcd7(","{\"response\":{\"Name\":\"abcd7(\"}}"));
    }
    private static int findPattern(String InputType, String InputValue, String responseString) {
        System.out.println("extractEncode" + responseString);
        int indexOfInputPattern = -1;
        String InputStringPattern = "InputType[\\W]*InputValue";
        InputStringPattern = StringUtils.replaceEach(InputStringPattern, new String[] { "InputType", "InputValue" },
                new String[] { InputType, InputValue });
        System.out.println(InputStringPattern);
        if (!StringUtils.isBlank(InputStringPattern)) {
            Pattern pattern = Pattern.compile(InputStringPattern);
             indexOfInputPattern = indexOf(pattern, responseString); 
        }
        return indexOfInputPattern;
    }

    private static int indexOf(Pattern pattern, String s) {
        System.out.println(pattern.toString()+" "+s);
        Matcher matcher = pattern.matcher(s);
        return matcher.find() ? matcher.end() : -1;
    }
}
Chris
  • 541
  • 1
  • 4
  • 11

2 Answers2

2

You can either escape the parentheses by adding a backslash in front of them or use Pattern.quote to escape parts you don't want to be interpreted as Pattern.

Read more here https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/regex/Pattern.html#quote(java.lang.String)

NielsNet
  • 818
  • 8
  • 11
1

If you're searching for brackets () in regular expressions, you have to escape them with a backslash \. So you search for Name\(. This is because brackets have a special meaning in regular expressions.

To make things more complicated, \ is a special character in Java Strings, so you may find you have to escape that too. So your final expression is likely to look like Name\\(.

squaregoldfish
  • 709
  • 8
  • 20