Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use preceding \K group negatively

Tags:

regex

ruby

Can I use the the preceding \K group negatively? Can I match the bar inside faxbar funbar bobar and bar and omit the bar inside foobar fobar foooooobar? https://regex101.com/r/qR9kD4/5

Regex

fo*\Kbar

String: (- and desired outcome)

foobar       - no match
fobar        - no match
foooooobar   - no match
faxbar       - match 'bar'
funbar       - match 'bar'
bobar        - match 'bar'
bar          - match 'bar'
dontmineidontwanttfooooobematchedaatall  - no match

Basically invert my current matches (apart from dontmineme...). Hoping I just need to add a ! or something!

like image 426
JayTarka Avatar asked Nov 26 '25 16:11

JayTarka


1 Answers

You can use \K with a Negative Lookahead assertion:

\b(?!fo+)\w*\Kbar

Demo

A simple solution would be to place what you want to ignore on the left side of the alternation and place what you want to match in a capturing group on the right side of the alternation operator.

fo+bar|\w*(bar)
like image 189
hwnd Avatar answered Nov 28 '25 15:11

hwnd



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!