C#正则表达式之间是否有换行符匹配 [英] C# Regex Match between with or without new lines
问题描述
我正在尝试在两个定界符 [%%]
之间匹配文本,并且无论字符串是否包含新行,我都想获取所有内容.
I am trying to match text between two delimiters, [% %]
, and I want to get everything whether the string contains new lines or not.
代码
string strEmailContent = sr.ReadToEnd();
string commentPatt = @"\[%((\r\n?|\n).*(\r\n?|\n))%\]";
Regex commentRgx = new Regex(commentPatt, RegexOptions.Singleline);
示例输入
//Successful
[%
New Comment
%] other content from input
//Match: [%\r\nNew Comment\r\n%]
//Fail
[% New Comment %]
//Match: false
//Successfully match single line with
string commentPatt = @"\[%(.*)%\]";
//Match: [% New Comment %]
我不知道如何组合这两种模式以匹配两种情况.任何人都可以提供帮助吗?
I do not know how to combine these two patterns to match both cases. Can anyone provide any assistance?
推荐答案
要在两个定界符之间获取文本,您需要将惰性匹配与.*?
一起使用,但要还匹配换行符号,您需要(?s)
单行修饰符,以便点也可以匹配换行符号:
To get text between two delimiters you need to use lazy matching with .*?
, but to also match newline symbols, you need (?s)
singleline modifier so that the dot could also match newline symbols:
(?s)\[%(.*?)%]
请注意,即使%
位于 [%...%]
.
请参见正则表达式演示.请注意,]
不必转义,因为它位于明确的位置,并且只能解释为原义的]
.
See regex demo. Note that the ]
does not have to be escaped since it is situated in an unambiguous position and can only be interpreted as a literal ]
.
在C#中,您可以使用
var rx = new Regex(@"(?s)\[%(.*?)%]");
var res = rx.Matches(str).Cast<Match>().Select(p => p.Groups[1].Value).ToList();
这篇关于C#正则表达式之间是否有换行符匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!