user1735921 user1735921 - 10 days ago 6
Ruby Question

Regular Expression in Atom Text Editor, exclude string "abc" from beginning of string

I have some code as follows:

data[:value] = some_val
data[:value_two] = someval2
data[:total_value_three] = someval3


I want to replace all code where total is not included,
I want the following result:

data[:total_value] = some_val
data[:total_value_two] = someval2
data[:total_value_three] = someval3


I have lot of such code in the text editor,
to replace that I have used this regular expression:

\[:[^total]([A-z_0-9]*)\]


And I am replacing it with this:

[:total_$1]


It is selecting the right data, but it is removing the first character, that is, it is becoming
total_alue
instead of
total_value
.

Answer

What you are looking for is negative look ahead. You can write it as

\[:(?!total)([A-z_0-9]*)\]

Regex Demo

  • (?!total) This is a negative look ahead. It checks whether : is not followed by a total.

What is wrong in [:[^total]([A-z_0-9]*)\]?

  • [^total] This is a negated character class. What it matches is one character, which is not t or o or a or l.
Comments