简体   繁体   中英

regex to match a character only if not followed by another character, then replace just that initial character

For instance,

(/=[^>]/, '═')

I'd like to keep that match, but only replace the equals sign with the double-horizontal-line. As it is, it matches any '=' that is followed by anything that isn't a '>' but then replaces both the '=' and the following character with the replacing character, I want to keep the following character, but replace just the '='. This is in ruby, if it makes any syntactic difference.

Example input:

= render :partial => 'file'

First = should be converted, second should be preserved

Depending on your regex library (I don't know Ruby), you may be able to use zero-width assertions:

/=(?!>)/

Note that this regex is slightly different to your regex, but it matches the description you gave in the title better. It will match any = that isn't followed by > . This includes matching an = at the end of the text, which your version won't match.

Like this? (I am using - instead of that special character you have):

Inside of irb:

ruby-1.9.2-p0 > "=x".gsub(/=([^>])/, '-\1')
 => "-x" 

ruby-1.9.2-p0 > "=>".gsub(/=([^>])/, '-\1')
 => "=>" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM