34

In C#, I write the following string to a string variable, carriage return and all:

asdfasdfasdf asdfas<test>asdfasdf asdfasdf<test>asdfasdf 

In Notepad2, I use this regular expression:

<test>.*<test> 

It selects this text as expected:

<test>asdfasdf asdfasdf<test> 

However, when I do this in C#:

System.Text.RegularExpressions.Regex.Replace(s, "<test>.*<test>", string.Empty); 

It doesn't remove the string. However, when I run this code on a string without any carriage returns, it does work.

So what I am looking for is a regex that will match ANY character, regardless whether or not it is a control code or a regular character.

3 Answers 3

60

You forgot to specify that the Regex operation (specifically, the . operator) should match all characters (not all characters except \n):

System.Text.RegularExpressions.Regex.Replace(s, "<test>.*<test>", string.Empty, RegexOptions.Singleline); 

All you needed to add was RegexOptions.Singleline.

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

1 Comment

Har! You're right! I'll mark your response as the answer in 10 minutes when stackoverflow allows it =P.
13

Use single-line mode:

Regex.Replace(s, "<test>.*<test>", "", RegexOptions.Singleline); 

Comments

0

You could remove the carriage returns in the string, then do your match:

s = s.Replace(Environment.NewLine, ""); 

Then it should work as expected:

System.Text.RegularExpressions.Regex.Replace(s, "<test>.*<test>", string.Empty); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.