C#条件Linq查询以获取括号内的值

本文关键字:获取 条件 Linq 查询 | 更新日期: 2023-09-27 18:19:42

我有一个字符串

美国奥兰多国际机场我想获得仅限代码的MCO如果字符串不包含代码,则返回空

正在寻找一个可以在一行中完成的linq查询

C#条件Linq查询以获取括号内的值

我更喜欢正则表达式。参见我的示例:

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 «')»
       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;