0

I need to extract VALUE1, VALUE2 and VALUE3 from the following multi-line string:

String input = "aa a\r\na aa \r\na getString(\"VALUE1\");aagetInt(\"VALUE2\");aa\r\n a getString(\"VALUE3\"); aaa\r\naaa";

I've tried:

Pattern pattern = Pattern.compile("\"(\\S+)\"+");
Matcher matcher = pattern.matcher(input);
while (matcher.find())
    System.out.println(matcher.group(1));

But this produces:

VALUE1\");aagetInt(\"VALUE2\");aa\r\n a getString(\"VALUE3

It takes everything between the first and last quotation marks.

Then I've tried this one:

"(.*)get(\\S+)\\(\"(\\S+)\"(.*)"

But this only takes the last match, VALUE3 (with matcher.group(3)).

How can I get all 3 values: VALUE1, VALUE2, VALUE3?

2
  • use Pattern.compile("\"([^\"])\""). Please note that this gets way more difficult if the real values of VALUE1 etc are allowed to contain a ". Commented Feb 3, 2022 at 14:01
  • 1
    Does this answer your question? Getting match of Group with Asterisk? Commented Feb 3, 2022 at 14:03

2 Answers 2

2

Your pattern was slightly off. Use this version:

String input = "aa a\r\na aa \r\na getString(\"VALUE1\");aagetInt(\"VALUE2\");aa\r\n a getString(\"VALUE3\"); aaa\r\naaa";
Pattern p = Pattern.compile("\\w+\\(\"(.*?)\"\\)");
Matcher m = p.matcher(input);
while (m.find())
    System.out.println(m.group(1));

This prints:

VALUE1
VALUE2
VALUE3
Sign up to request clarification or add additional context in comments.

Comments

1

Using \S+ matches all non whitespace chars, and using .* matches to the end of the line first, so in both pattern you are matching too much.

Getting the value in parenthesis that starts with get and using non greedy \S+? (note that is does not match spaces):

get[^\s()]*\("(\S+?)"\)

Regex demo

Example:

String input = "aa a\r\na aa \r\na getString(\"VALUE1\");aagetInt(\"VALUE2\");aa\r\n a getString(\"VALUE3\"); aaa\r\naaa";
String regex = "get[^\\s()]*\\(\"(\\S+?)\"\\)";

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);

while (matcher.find()) {
   System.out.println(matcher.group(1));            
} 

Output

VALUE1
VALUE2
VALUE3

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.