微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

LINQ可以用于搜索字符串中的Regex表达式吗?

如何解决LINQ可以用于搜索字符串中的Regex表达式吗?

我有以下有效的代码,但想使用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);

有什么建议吗?

在此先感谢您的帮助

解决方法

可以。不过最好使用查询语法,如此处所述: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-]+. *"
,

您的正则表达式应修改为

^[\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•-])");

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。