"-dhello;-egoodbye;-lcul8r" -replace "-d.*;","-dbonjour;"
gives:
-dbonjour;-lcul8r
Is it possible to not have it get rid of goodbye
?
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,}?.
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.
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.
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.
You should make the matching lazy using ?
.
Use:
"-dhello;-egoodbye;-lcul8r" -replace "-d.*?;","-dbonjour;"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With