Suppose I have following code :
string input = "hello everyone, hullo anything";
string pattern = "h.llo [A-z]+";
string output = Regex.Replace(input,pattern,"world");
(I have tried to make it as simple as possible)
Above code output is "world, world" while what I really want is a way to change all words following by h.llo to world and I want output to be "hello world, hullo world"
I was looking for a way to do this and I searched a lot and read this article:
Replace only some groups with Regex
But I didn't get much from it and I'm not sure it's exactly what I want.
Is there any approach at all?
Change your code to,
string input = "hello everyone, hullo anything";
string pattern = "(h.llo )[A-Za-z]+";
string output = Regex.Replace(input,pattern,"$1world");
[A-z] matches not only A-Z, a-z but also some other extra characters.
or
string pattern = "(?<=h.llo )[A-Za-z]+";
string output = Regex.Replace(input,pattern,"world");
(?<=h.llo ) positive lookbehind asserion which asserts that the match must be preceded by h, any char, llo , space. Assertions won't match any single character but asserts whether a match is possible or not.
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With