问题描述
我有以下有效的代码,但想使用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•-])");