Ruby regex how to exclude hit with quotes
Ruby regex how to exclude hit with quotes
I face new challenge how to select only single word PATIENT from my sample string, so I need ignore if it's literal in single quotes and single sweep if possible. It also need to be word only and it solved already with b
switch. Tried pretty much all I could on rubular.com. do you think it's doable. Best.M
b
s = 'alpha 'patient' #1 literal PATIENT and As patieNT and patientXX '
regex=/bpatientb/i
regex =/(?<!['"])bpatientb(?!['"])/ ##!!!! solved (c) emsimpson92
puts s.scan(regex) # select only PATIENT only without qoutes
Updated: I use heat of the moment to solve another case how skip case when regex word preceded by As
(but with 1+ spaces), how I can add 1 ore more space
condition into my first part, I tried s+
but it doesn't work here:
(?<!ass) (?<!['"])bpatientb
## `AS with 1+ spaces
As
1 ore more space
s+
(?<!ass) (?<!['"])bpatientb
1 Answer
1
This should give you what you're looking for. (?<!['"])patient(?!['"])
(?<!['"])patient(?!['"])
Demo
Tx much emS!!! works perfectly and with b as well (?<!['"])bpatientb(?!['"]). I never see ? in regex manuals. Sorry can't give your 10 stars,I'm not qualified yet!!!
– Mich28
Sep 7 '18 at 21:59
(?<!somepattern)
means your desired result is not preceded by "somepattern" and (?!somepattern)
means your desired result is not followed by "somepattern". They're called negative lookaheads/lookbehinds– emsimpson92
Sep 7 '18 at 22:01
(?<!somepattern)
(?!somepattern)
Tx again!!! Really super!!! Glad somebody already gave you +1 score.
– Mich28
Sep 7 '18 at 22:04
“I never see ? in regex manuals.”—it’s literally impossible to find the regex manual consisting of at least 100 words that does not mention
?
. Also, if the answer helped, you are supposed to mark it as correct with a greeny check under the score.– Aleksei Matiushkin
Sep 8 '18 at 3:59
?
Tx again all, I did more testing and realized that you can't use range
1,
inside of lookahead, this always give an error (?<!as[ ]2,)
– Mich28
Sep 8 '18 at 4:40
1,
(?<!as[ ]2,)
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
regular-expressions.info/lookaround.html
– Aleksei Matiushkin
Sep 8 '18 at 4:00