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?

Wolf359
  • 2,620
  • 4
  • 42
  • 62
  • use `Pattern.compile("\"([^\"])\"")`. Please note that this gets way more difficult if the real values of `VALUE1` etc are allowed to contain a `"`. – f1sh Feb 03 '22 at 14:01
  • 1
    Does this answer your question? [Getting match of Group with Asterisk?](https://stackoverflow.com/questions/25858345/getting-match-of-group-with-asterisk) – Vikstapolis Feb 03 '22 at 14:03

2 Answers2

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
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
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
The fourth bird
  • 154,723
  • 16
  • 55
  • 70