Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set RegEx in Java to be non-greedy by default

Tags:

java

string

regex

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?
like image 544
Basti Funck Avatar asked Mar 04 '26 16:03

Basti Funck


1 Answers

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

parameter:\\s+(.*?)\\s+(result|client|user):
like image 143
M A Avatar answered Mar 06 '26 07:03

M A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!