Home > Software design >  gsub all instances of substring once
gsub all instances of substring once

Time:08-24

My goal is to replace all instances of the substring "test_" to "append.test_". This can occur multiple times in a sentence. For example:

I am test_a and test_b => I am append.test_a and append.test_b

The problem is that I can have something like this

I am test_a and I am test_b_test_c

I can't figure out the right regex because when I try to use my_string.gsub('test_', "append.test_") it returns

I am append.test_a and I am append.test_b_append.test_c

My expected result:

I am append.test_a and I am append.test_b_test_c

Any ideas?

CodePudding user response:

Assuming that you wish to avoid replacing in situations where nothing else precedes test_ in a string, you can use \b to check for a word boundary before test_.

s = "I am test_a and I am test_b_test_c"

s.gsub(/\btest_/, "append.test_")
# => "I am append.test_a and I am append.test_b_test_c"

CodePudding user response:

You can try this regex pattern:

/(^| )test_/

my_string.gsub(/(^| )test_/, "\1append.test_")

  • Related