Flethuseo
Flethuseo

Reputation: 6199

Regex to replace some instances of a word but not others

I am trying to figure out a regular expression to replace the word contained in some strings from "Name1" to "N1", in RUBY:

Name1_Instance_1 --> N1_Instance_1
Name1_Instance_2 --> N1_Instance_2

But not if the string contains a .xml at the end:

Name1.xml
Name1_Instance.xml

I've tried this:

Name1[\w_]*[^.xml]

But it doesn't exclude this case

Name1_Instance.xml

Upvotes: 0

Views: 77

Answers (3)

Justin O Barber
Justin O Barber

Reputation: 11601

Try something along these lines:

Name(?=\d+)(?!\w*\.xml)

Here I used a lookahead assertion ((?=\d+)) to see if one or more digits follows Name, and then I used a negative lookahead assertion ((?!\w*\.xml)) to exclude any item that ends in .xml. Lookahead assertions of any variety do not consume any of the string and do not return any part of the lookahead assertion in the result.

In Ruby, you can do this:

t = """Name1_Instance_1    
.. .. .. .. Name1_Instance_2    
.. .. .. .. Name1.xml    
.. .. .. .. Name1_Instance.xml""".gsub /Name(?=\d+)(?!\w*\.xml)/, 'N'

print t
N1_Instance_1   
.. .. .. N1_Instance_2   
.. .. .. Name1.xml   
.. .. .. Name1_Instance.xml

Upvotes: 2

AndyJW
AndyJW

Reputation: 191

You could use a negative lookahead that looks like:

Name1[\w]*(?!\.xml)

Upvotes: 1

crackmigg
crackmigg

Reputation: 5901

You can try this:

Name1\w*(?!\.xml)

?! is the negative lookahead.

Upvotes: 1

Related Questions