Monday, 15 February 2010

ruby - Regex to replace some instances of a word but not others -



ruby - Regex to replace some instances of a word but not others -

i trying figure out regular look replace word contained in strings "name1" "n1", in ruby:

name1_instance_1 --> n1_instance_1 name1_instance_2 --> n1_instance_2

but not if string contains .xml @ end:

name1.xml name1_instance.xml

i've tried this:

name1[\w_]*[^.xml]

but doesn't exclude case

name1_instance.xml

try along these lines:

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

here used lookahead assertion ((?=\d+)) see if 1 or more digits follows name, , used negative lookahead assertion ((?!\w*\.xml)) exclude item ends in .xml. lookahead assertions of variety not consume of string , not homecoming part of lookahead assertion in result.

in ruby, can 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

ruby regex

No comments:

Post a Comment