Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make Regex replace non-greedy?

"-dhello;-egoodbye;-lcul8r" -replace "-d.*;","-dbonjour;"

gives:

-dbonjour;-lcul8r

Is it possible to not have it get rid of goodbye?

like image 839
muhmud Avatar asked Mar 06 '13 11:03

muhmud


People also ask

How do I make something not greedy in regex?

To make the quantifier non-greedy you simply follow it with a '?' the first 3 characters and then the following 'ab' is matched. greedy by appending a '?' symbol to them: *?, +?, ??, {n,m}?, and {n,}?.

Can you use regex to replace?

How to use RegEx with . replace in JavaScript. To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring.

Is regex matching greedy?

The standard quantifiers in regular expressions are greedy, meaning they match as much as they can, only giving back as necessary to match the remainder of the regex. By using a lazy quantifier, the expression tries the minimal match first.

How do you make a non-greedy python regex?

Non-greedy quantifiers match their preceding elements as little as possible to return the smallest possible match. Add a question mark (?) to a quantifier to turn it into a non-greedy quantifier.


2 Answers

You should make the matching lazy using ?.

Use:

"-dhello;-egoodbye;-lcul8r" -replace "-d.*?;","-dbonjour;"
like image 52
deadlock Avatar answered Nov 09 '22 21:11

deadlock


Always be explicit. .* matches everything it can (including the semicolon and all that follows), but you only want to match until the next semicolon, so just tell the regex engine that:

"-dhello;-egoodbye;-lcul8r" -replace "-d[^;]*;","-dbonjour;"

[^;] matches any character except semicolon.

like image 23
Tim Pietzcker Avatar answered Nov 09 '22 21:11

Tim Pietzcker