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)
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:
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
\bmetacharacter 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:
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.