8

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

10
  • Why do you think regex is the right tool? Commented Jan 1, 2012 at 8:22
  • 1
    "sometextREPLACEsomeothertext".Replace("REPLACE", "OtherText") Commented Jan 1, 2012 at 8:23
  • @MatthiasKoch it does not , it will replace all the REPLACE text which is not what want, for example, if i have sometext_REPLACE_someotherText_one_REPLACE_two , it will replace all the REPLACE text. Commented Jan 1, 2012 at 8:27
  • @Oded other ideas are welcome as well :) Commented Jan 1, 2012 at 8:31
  • 1
    You need to clarify your question - add example of what shouldn't be changing etc... Commented Jan 1, 2012 at 8:33

2 Answers 2

9

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");
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this is pretty close, but still it seems like greedy match, can you make it lazy one.
0

This is the regex to test if the string is valid.

\^.REPLACE.\

C# replace

string s = "sdfsdfREPLACEdhfsdg";
string v = s.Replace("REPLACE", "SOMETEXT");

1 Comment

Can't you just go s.Replace("sometext_REPLACE_other text", "sometext_TEXT_othertext")?

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.