4

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?

1 Answer 1

5

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

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

1 Comment

Thank you it worked as expected. Yes I know that, I just did this for the sake of simplicity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.