Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Replace in between

Tags:

c#

regex

I have been trying real hard understanding regular expression, Is there any way I can replace character(s) that is between two strings/ For example I have

sometextREPLACEsomeothertext

I want to replace , REPLACE (which can be anything in real work) ONLY between sometext and someothertext with other string. Can anyone please help me with this.

EDIT Suppose, my input string is

sometext_REPLACE_someotherText_something_REPLACE_nothing

I want to replace REPLACE text in between sometext and someotherText resulting following output

sometext_THISISREPLACED_someotherText_something_REPLACE_nothing

Thank you

like image 469
41K Avatar asked Jan 01 '12 08:01

41K


1 Answers

If I understand your question correctly you might want to use lookahead and lookbehind for your regular expression

(?<=...)   # matches a positive look behind
(?=...)    # matches a positive look ahead

Thus

(?<=sometext)(\w+?)(?=someothertext)

would match any 'word' with at least 1 character following 'sometext' and followed by 'someothertext'

In C#:

result = Regex.Replace(subject, @"(?<=sometext)(\w+?)(?=someothertext)", "REPLACE");
like image 113
Ingo Avatar answered Sep 29 '22 11:09

Ingo