【问题标题】:C# Conditional Linq query to get value inside parenthesisC# 条件 Linq 查询以获取括号内的值
【发布时间】:2012-01-06 15:12:02
【问题描述】:

我有一个字符串

“美国奥兰多国际机场 (MCO) 奥兰多” 我只想获取代码 MCO 如果字符串不包含代码,则返回 null

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

【问题讨论】:

  • 不要使用 LINQ。使用简单的字符串方法或正则表达式。
  • 你确定它一定是LINQ吗?正则表达式是一个更好的工具。
  • 我不确定你在问什么。您想从多个字符串中获取代码(在 () 之间),还是希望从这个特定字符串中获取 MCO?如果这是最后一种情况,RegEx 将是您的最佳选择。
  • @kendfrey 好的,哪一个应该有更好的性能和速度 regex 或 linq ?
  • @Pbirkoff 来自多个字符串

标签: c# linq


【解决方案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 «\)»

【讨论】:

  • 在上面的正则表达式中什么是“部分”
  • Part 将是您的输入字符串。 resultString 包含请求的值。我在示例中添加了部分字符串。
【解决方案2】:
       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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    • 1970-01-01
    • 2021-04-26
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多