0

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==

1 Answer 1

1

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
  "                        '"'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.