0

How can I use Regex.Replace to achieve the flowing: Given the input string:

"DV_DHW dv_DWH dv_dwh Dv_Dwh some more text dv_dwhtest"

I want to change it to :

"Test_DV_DHW Test_DV_DHW Test_DV_DHW Test_DV_DHW  some more text dv_dwhtest"

I tried this:

Regex.Replace("Test_DV_DHW Test_DV_DHW Test_DV_DHW Test_DV_DHW  some more text dv_dwhtest", "DV_DHW", "Test_DV_DHW", RegexOptions.IgnoreCase);

But it replace just the first instance of DV_DHW (case sensitive)

0

1 Answer 1

1

Your input contains "DV_DHW" and "DV_DWH". Those aren't the same string. Notice that the first is D-H-W, where "H" is before "W", and the second has "W" before "H."

Since they're not the same, only the first occurrence of "DV_DHW" gets replaced. The correct output is:

Test_DV_DHW dv_DWH dv_dwh Dv_Dwh some more text dv_dwhtest

If your intention was to replace both of the strings, expect the last one since it isn't a whole word, you could use this pattern: @"\bDV_D(?:HW|WH)\b"

The \b metacharacter matches a word-boundary and then the pattern uses (?:...) for a non-capturing group that will match either "HW" or "WH" text.

The above pattern would produce this output:

Test_DV_DHW Test_DV_DHW Test_DV_DHW Test_DV_DHW some more text dv_dwhtest

Notice that the last word, "dv_dwhtest," hasn't been modified since the "dv_dwh" wasn't a whole word and was a part of a word instead.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.