Giuseppe
Giuseppe

Reputation: 5348

Regex: match something except within arbitrary delimiters

My string:

a = "Please match spaces here <but not here>. Again match here <while ignoring these>"

Using Ruby's regex flavor, I would like to do something like:

a.gsub /regex_pattern/, '_'

And obtain:

"Please_match_spaces_here_<but not here>._Again_match_here_<while ignoring these>"

Upvotes: 0

Views: 79

Answers (2)

Alan Moore
Alan Moore

Reputation: 75232

This should do it:

result = subject.gsub(/\s+(?![^<>]*>)/, '_')

This regex assumes there's nothing tricky like escaped angle brackets. Also be aware that \s matches newlines, TABs and other whitespace characters as well as spaces. That's probably what you want, but you have the option of matching only spaces:

/ +(?![^<>]*>)/

Upvotes: 2

Bartłomiej Gładys
Bartłomiej Gładys

Reputation: 4615

I think, it works:

a = "Please match spaces here <but not here>. Again match here <while ignoring these>"

pattern = /<(?:(?!<).)*>/

a.gsub(pattern, '')
# => "Please match spaces here . Again match here "

Upvotes: 0

Related Questions