简体   繁体   中英

C# regular expression to match ANY character?

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.

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 .

Use single-line mode:

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM