Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# LINQ可以用于搜索字符串中的正则表达式吗?_C#_Regex_Linq - Fatal编程技术网

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}•-]
    -字母、空格、
    -
在C#中,使用

如果只需要在字符串开头允许
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•-])");