Use previous group \ K negatively
Can the previous group \ K be used negatively? Is it possible to combine the bar
inside faxbar
funbar
bobar
and bar
and lower the panel inside foobar
fobar
foooooobar
? https://regex101.com/r/qR9kD4/5
Regex
fo*\Kbar
Line: (- and desired result)
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 current matches (except dontmineme...
). Hope I just need to add !
or something!
source to share
If you can use bindings, it might be doable. They allow you to make sure bar
you look into the lookahead - which is the same bar
you use in the main regex:
^(?!fo+bar$)[a-z]*\Kbar$ \b(?!fo+bar\b)[a-z]*\Kbar\b
If you cannot use bindings, it might not be possible. We'll need to know a lot more about the types of strings you expect to see, as well as more detailed criteria for matching them.
But I have to ask, do you really need to use \K
? Lookarounds may seem like an obvious approach, but it is often much easier to use capture groups.
\b(?!fo+bar\b)[a-z]*(bar)\b
You just use $~[1]
instead $&
to extract the substring you are interested in.
source to share
This should do it:
R = /^fo|bar/
str[R]=='bar'
although he doesn't use \K
.
[
['foobar', false],
['fobar', false],
['foooooobar', false],
['faxbar', true ],
['funbar', true ],
['bobar', true ],
['bar', true ],
['dontmineidontwanttfooooobematchedaatall', false],
].each { |str,result| (str[R]=='bar') == result }
true
true
...
true
Others suggesting answers might want to use my test code.
source to share