Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace only a part of matched regular expression in c#

Tags:

c#

regex

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?

like image 695
Saeed mohammadi Avatar asked Oct 27 '25 03:10

Saeed mohammadi


1 Answers

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

like image 143
Avinash Raj Avatar answered Oct 29 '25 19:10

Avinash Raj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!