0

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?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
rsarmiento
  • 13
  • 4
  • Your question is incomplete. What is the desired result for the string, `"test_a test_ test_1 test_@ attest_c :test_d"`? The problem is that you are expressing the question in terms of a couple of examples. That is rarely sufficient for a question to be precise and unambiguous. You need to state your question in words and then use examples merely for illustration. You may find that difficult but it is a skill you need to master to prepare specifications for computer programs. – Cary Swoveland Aug 23 '22 at 05:06
  • 1
    The tag "string" is redundant since you have "regex". I think I'd probably just have "ruby" and "regex" but I suppose a case could be made that someone may also use "gsub" in a search. – Cary Swoveland Aug 23 '22 at 05:33
  • Does this answer your question? [Regex match entire words only](https://stackoverflow.com/questions/1751301/regex-match-entire-words-only) – Wiktor Stribiżew Aug 23 '22 at 20:08
  • There are several reasons to wait at least a few hours before selecting an answer. There's no rush. – Cary Swoveland Aug 23 '22 at 21:20

1 Answers1

2

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"
Chris
  • 26,361
  • 5
  • 21
  • 42