C# LINQ可以用于搜索字符串中的正则表达式吗?
我有下面的代码可以使用,但我想使用C# LINQ可以用于搜索字符串中的正则表达式吗?,c#,regex,linq,C#,Regex,Linq,我有下面的代码可以使用,但我想使用LINQ对其进行编辑,以查找目标中是否有Regex搜索字符串 foreach (Paragraph comment in wordDoc.MainDocumentPart.Document.Body.Descendants<Paragraph>().Where<Paragraph>(comment => comment.InnerText.Contains("cmt"))) { /
LINQ
对其进行编辑,以查找目标中是否有Regex
搜索字符串
foreach (Paragraph comment in
wordDoc.MainDocumentPart.Document.Body.Descendants<Paragraph>().Where<Paragraph>(comment => comment.InnerText.Contains("cmt")))
{
//print values
}
有什么建议吗
提前感谢您提供的任何帮助。但最好使用查询语法,如下所述: 例如:
var queryMatchingFiles =
from file in fileList
where file.Extension == ".htm"
let fileText = System.IO.File.ReadAllText(file.FullName)
let matches = searchTerm.Matches(fileText)
where matches.Count > 0
select new
{
name = file.FullName,
matchedValues = from System.Text.RegularExpressions.Match match in matches
select match.Value
};
您的模式很好,只需从末尾删除$
,然后添加任何字符
@"^[a-zA-Z-]+. *"
您的正则表达式应修改为
^[\p{L}•-]
若要在字符串开头允许空白,请添加\s
并使用
^[\p{L}\s•-]
详细信息
-字符串的开头^
-一封信,[\p{L}•-]
或•
-
-字母、空格、[\p{L}•-]
或•
-
cmt
:
var reg = new Regex(@"^(?:cmt|[\p{L}\s•-])");
非常感谢你的帮助。很抱歉,我不明白:我需要用你的例子来替换我的
foreach
,或者什么?请给我解释一下……非常感谢您的回复。您的regexp
工作正常,但很抱歉,现在我需要通过LINQ
检查select,如果字符串以字母开头或以符号开头-
或•
或空白
,我已经尝试过,但没有成功^[\p{L}-]
,并且您的regexp
没有验证重音字符(变音符号)因为E'
@Kooper变音符号已经是第二个字符了,所以如果第一个字符是一个字母,它已经可以了。要检查字符串是否以空格开头,请始终使用^[\p{L}\s•-]
。有一点不清楚:您有注释=>comment.InnerText.Contains(“cmt”)
它获取字符串中任何位置包含cmt
的项目,但在您看来字符串应该以cmt
开头。这是因为这些项目适用于不同的场景吗?
var reg = new Regex(@"^[\p{L}•-]");
foreach (Paragraph comment in
wordDoc.MainDocumentPart.Document.Body.Descendants<Paragraph>()
.Where<Paragraph>(comment => reg.IsMatch(comment.InnerText)))
{
//print values
}
var reg = new Regex(@"^(?=.*cmt)[\p{L}\s•-]", RegexOptions.Singleline);
var reg = new Regex(@"^(?:cmt|[\p{L}\s•-])");