1

I have Strings like the following:

"parameter: param0=true, param1=401230 param2=asset client: desktop"
"parameter: param0=false, param1=15230 user: user213 client: desktop"
"parameter: param0=false, param1=51235 param2=asset result: ERROR"

The pattern is parameter:, then the param's, and after the params either client: and/or user: and/or result.

I want to match the stuff between parameter: and the first occurrence of either client:, user: or result:

So for the 2nd String it should match param0=false, param1=15230.

My regex is:

parameter:\s+(.*)\s+(result|client|user):

But now if I match the 2nd String it captures param0=false, param1=15230 user: user213 (looks like regex is matching greedy)

  1. How to fix this? parameter:\s+(.*)\s+(result|client|user)+?: won't fix it
  2. With this regex tester I can add the modifier U to the regex to make regex lazy by default, is this possible in Java too?
Unihedron
  • 10,251
  • 13
  • 53
  • 66
Basti Funck
  • 1,244
  • 15
  • 26

2 Answers2

4

Try putting the ? character inside the first captured group (the subpattern you intend to extract):

parameter:\\s+(.*?)\\s+(result|client|user):
M A
  • 65,721
  • 13
  • 123
  • 159
3

No. There is no ungreedy modifier in Java. You have to use ? behind modifiers to make the quantifiers as lazy capture.

This means you should denote all quantifiers with a ?, see the following pattern:

"parameter:\\s+?(.*?)\\s+?(result|client|user):"

Specified by:
http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

Unihedron
  • 10,251
  • 13
  • 53
  • 66