3

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?

Community
  • 1
  • 1
Saeed mohammadi
  • 199
  • 1
  • 13

1 Answers1

4

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

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274