返回带换行符的 RegExp C#

本文关键字:RegExp 换行符 返回 | 更新日期: 2023-09-27 17:55:11

我在 C# 中使用正则表达式时遇到了问题。我有一个表示页面(HTML等)的字符串。该字符串还包含不同位置的 ''r'、''r 和 ',现在我正在尝试匹配字符串中的某些内容:

Match currentMatch = Regex.Match(contents, "Title: <strong>(.*?)</strong>");
string org = currentMatch.Groups[1].ToString();

这工作正常,但是,当我想匹配字符串中具有前面提到的任何字符(换行符)的内容时,它不会返回任何内容(空,不匹配):

Match currentMatch = Regex.Match(contents, "Description: <p>(.*?)</p>");
string org = currentMatch.Groups[1].ToString();

但是,如果我在匹配项上方添加以下行,它确实有效:

contents = contents.Replace("'r", " ");
contents = contents.Replace("'n", " ");

但是我不喜欢它修改源代码,我该怎么办?

返回带换行符的 RegExp C#

默认情况下

.与换行符不匹配。您可以使用正则表达式选项Singleline 来更改此设置。这会将整个输入字符串视为一行,即点也与换行符匹配。

Match currentMatch = Regex.Match(contents, "Title: <strong>(.*?)</strong>", RegexOptions.Singleline);

顺便说一句,我希望你知道正则表达式通常不是处理 HTML 的方法?