C# Linq 语句中的正则表达式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16922818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regex in Linq statement?
提问by jerryh91
I'm writing a short C# to parse a given XML file. But 1 of the tag values can change, but always includes words "Fast Start up" (disregarding case and spaces, but needs to be in the same order) in the where clause. I'm not sure how I would do this in a sql like statement in C#.
我正在编写一个简短的 C# 来解析给定的 XML 文件。但是其中 1 个标记值可以更改,但始终在 where 子句中包含“快速启动”字样(不考虑大小写和空格,但需要按相同顺序)。我不确定如何在 C# 中的类似 sql 的语句中执行此操作。
var selected = from cli in doc.Descendants(xmlns+ "Result")
where cli.Element(xmlns + "ResultsLocation").Value == "Assessments-Fast-Startup"
select cli;
采纳答案by Dave Bish
Assuming you are looking for the exact string - can you just use a String.Contains?
假设您正在寻找确切的字符串 - 您可以使用String.Contains?
var selected = from cli in doc.Descendants(xmlns+ "Result")
where cli.Element(xmlns + "ResultsLocation").Value.Contains("Assessments-Fast-Startup")
select cli;
Otherwise, something like:
否则,类似于:
var rx = new Regex("fast(.*?)startup", RegexOptions.IgnoreCase);
var selected = from cli in doc.Descendants(xmlns+ "Result")
where rx.IsMatch(cli.Element(xmlns + "ResultsLocation").Value)
select cli;
回答by MikeM
a regex of fast[- ]?start[- ]?upshould work
fast[- ]?start[- ]?up应该工作的正则表达式
where an optional dashor spacecould be separating the word parts
可选的破折号或空格可以分隔单词部分
...
where Regex.IsMatch(
cli.Element(xmlns + "ResultsLocation").Value,
"fast[- ]?start[- ]?up",
RegexOptions.IgnoreCase
)
select cli
if you find you need to tweak the regex try a regex tester like http://regexpal.com/
如果您发现需要调整正则表达式,请尝试使用正则表达式测试器,例如http://regexpal.com/
As @DaveBish has mentioned you might be fine with .Contains(...)test instead of a regex or even .ToLower().Contains(...)chaining (you may also need a nullcheck as well)
正如@DaveBish 所提到的,您可能对.Contains(...)test 而不是正则表达式甚至.ToLower().Contains(...)链接没问题(您可能还需要null检查)

