Reputation: 6199
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
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
Reputation: 191
You could use a negative lookahead that looks like:
Name1[\w]*(?!\.xml)
Upvotes: 1
Reputation: 5901
You can try this:
Name1\w*(?!\.xml)
?!
is the negative lookahead.
Upvotes: 1