简体   繁体   English

C# 正则表达式匹配任何字符?

[英]C# regular expression to match ANY character?

In C#, I write the following string to a string variable, carriage return and all:在 C# 中,我将以下字符串写入字符串变量、回车和所有内容:

asdfasdfasdf
asdfas<test>asdfasdf

asdfasdf<test>asdfasdf

In Notepad2, I use this regular expression:在 Notepad2 中,我使用这个正则表达式:

<test>.*<test>

It selects this text as expected:它按预期选择此文本:

<test>asdfasdf

asdfasdf<test>

However, when I do this in C#:但是,当我在 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):您忘记指定 Regex 操作(特别是.运算符)应匹配所有字符(不是\n 之外的所有字符):

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

All you needed to add was RegexOptions.Singleline .您需要添加的只是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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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