Reputation: 13
I need to parse multiple if and else if entries in machine generated code to extract eventName values. All I care about is an infinite amount of combinations of whats contained in quotes in my string below.
Consider the following code:
String input = "if (eventName== \"event1\") {//blahblah\n}\nelse if (eventName==\"event2\") {//blahblah\n }";
String strPattern = "eventName(?s)==.*\"(.*)\"";
Pattern pattern = Pattern.compile(strPattern,Pattern.CASE_INSENSITIVE);
Matcher match = pattern.matcher(input);
while (match.find()) {
System.out.printf("group: %s%n", match.group(1));
}
This only gives me the second captured group event2. How can I achieve parsing the above with all the combinations of whitespace and line feeds that could be in between eventName==
Upvotes: 0
Views: 49
Reputation: 46841
You can try non-greedy way
String strPattern = "eventName(?s)==.*?\"(.*?)\"";
Or
String strPattern = "eventName==\\s*\"([^\"]*)\"";
output:
group: event1
group: event2
Second Regex Pattern Explanation:
eventName== 'eventName=='
\s* whitespace (\n, \r, \t, \f, and " ") (0 or more times)
" '"'
( group and capture to \1:
[^"]* any character except: '"' (0 or more times)
) end of \1
" '"'
Upvotes: 1