Giuseppe Giuseppe - 2 years ago 156
Ruby Question

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>"

Answer Source

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:

/ +(?![^<>]*>)/
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download