【问题标题】:Can LINQ be used to search for Regex expressions in a string?可以使用 LINQ 在字符串中搜索 Regex 表达式吗?
【发布时间】:2021-01-06 08:00:42
【问题描述】:

我有以下有效的代码,但想使用LINQ 对其进行编辑,以查找是否有任何Regex 搜索字符串在目标中。

foreach (Paragraph comment in
            wordDoc.MainDocumentPart.Document.Body.Descendants<Paragraph>().Where<Paragraph>(comment => comment.InnerText.Contains("cmt")))
{
    //print values
}

更准确地说,如果字符串以字母开头还是以符号开头-,我必须通过LINQ 进行选择

这个Regex 适合我的情况吗?

string pattern = @"^[a-zA-Z-]+$";
Regex rg = new Regex(pattern);

有什么建议吗?

提前感谢您的帮助

【问题讨论】:

  • 有一点不清楚:你有comment =&gt; comment.InnerText.Contains("cmt"),它会在字符串中的任何地方获取包含cmt的项目,但是在your next question中你说字符串应该以cmt开头。是因为这些是针对不同场景的吗?

标签: c# regex linq


【解决方案1】:

你可以。不过最好使用查询语法,如下所述:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/how-to-combine-linq-queries-with-regular-expressions

例子:

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-]+. *"

【讨论】:

  • 非常感谢您的帮助。对不起,但我不明白:我需要用你的例子替换我的foreach 还是什么?请解释我...
【解决方案2】:

你的正则表达式应该修改为

^[\p{L}•-]

要在字符串的开头添加空格,添加 \s 并使用

^[\p{L}\s•-]

详情

  • ^ - 字符串开头
  • [\p{L}•-] - 一封信,-
  • [\p{L}•-] - 字母、空格、-

在 C# 中,使用

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
}

如果你想匹配那些包含cmt的项目并且也匹配这个正则表达式,你可以将模式调整为

var reg = new Regex(@"^(?=.*cmt)[\p{L}\s•-]", RegexOptions.Singleline);

如果您只需要在字符串开头允许cmt

var reg = new Regex(@"^(?:cmt|[\p{L}\s•-])");

【讨论】:

  • 非常感谢您的回复。您的regexp 工作正常,但我很抱歉,但现在我需要通过LINQ 检查选择字符串是否以字母开头或以符号开头-whitespace,我试过没有成功@987654342 @
  • 而您的 regexp 不会将重音字符(变音符号)验证为 E’
  • @Kooper Diacritic 已经是第二个字符,所以如果第一个是字母,就已经可以了。要检查字符串是否以空格开头,请使用^[\p{L}\s•-]。总是put hyphen at the closing bracket
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-17
  • 1970-01-01
  • 1970-01-01
  • 2016-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多