Ruby regex: "grab a string if it doesn't follow ..."

My regular expression captures quoted phrases:

"([^"]*)" 

I want to improve it by ignoring quotes followed by ", -" (comma, space and dash in that particular order).

How to do it?

Test: http://rubular.com/r/xls6vN1w92

+6
ruby regex
source share
4 answers

This should do it using Negative Lookahead :

 "(?!, -)([^"]*)"(?!, -) 

A little bad, but it works. You want to make sure that none of the quotes is followed by your line, otherwise the match will start with closed quotes.

http://rubular.com/r/yFMyUKJOHL

+4
source share

Regex

"(.*?)"(?!, -)

Working example

http://rubular.com/r/9kOmZLxLfy

+1
source share

It is impossible to do in your context, its open end. The only way to make it out is to use it not the way you want, but its still unacceptable premise.

/"([^"]*?)"(?!, -)|"[^"]*?"(?=, -)/

Then check for capture group 1 in each match, something like this:

 $rx = qr/"([^"]*?)"(?!, -)|"[^"]*?"(?=, -)/; while (' "ingnore me", - "but not me" ' =~ /$rx/g) { print "'$1'\n" if defined $1 } 
+1
source share

Add (?!...) to the end of the regular expression:

 "([^"\n]*)"(?!, -) 
0
source share

All Articles