我有一个字符串
“奥兰多,奥兰多国际机场(MCO),美国” 我想得到的代码只有MCO 如果string不包含代码,则返回null
寻找可以在一行中执行的linq查询
答案 0 :(得分:1)
var value = "Orlando, Orlando International Airport(MCO), United States";
var result = from p in value.Split(',')
let flg = p.IndexOf("(MCO)") > -1
select flg ? p : null;
答案 1 :(得分:1)
我更喜欢正则表达式。看我的例子:
string resultString = null;
try
{
string part = "Orlando, Orlando International Airport(MCO), United States";
resultString = Regex.Match(part, @"(?<=\().*(?=\))", RegexOptions.IgnoreCase | RegexOptions.Multiline).Value;
}
catch (ArgumentException ex)
{
// Syntax error in the regular expression
}
对于表达式的文档:
// (?<=\().*(?=\))
//
// Options: case insensitive; ^ and $ match at line breaks
//
// Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=\()»
// Match the character “(” literally «\(»
// Match any single character that is not a line break character «.*»
// Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
// Assert that the regex below can be matched, starting at this position (positive lookahead) «(?=\))»
// Match the character “)” literally «\)»