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;
}
}