我有一個字符串C#條件的LINQ查詢來獲取值在括號內
「奧蘭多,奧蘭多國際機場(MCO),美國」 我想要得到的代碼只MCO 此外,如果字符串不包含代碼然後返回null
尋找LINQ查詢,可以做到在一個行
我有一個字符串C#條件的LINQ查詢來獲取值在括號內
「奧蘭多,奧蘭多國際機場(MCO),美國」 我想要得到的代碼只MCO 此外,如果字符串不包含代碼然後返回null
尋找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 «\)»
在上面的正則表達式什麼是「部分」 – 2012-01-06 15:24:46
部分將是您的輸入字符串。 resultString包含請求的值。我在示例中添加了部分字符串。 – Aphelion 2012-01-06 15:36:58
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;
不要使用LINQ。使用簡單的字符串方法或正則表達式。 – 2012-01-06 15:15:31
你確定它一定是LINQ嗎?正則表達式是一個更好的工具。 – dasblinkenlight 2012-01-06 15:15:44
我不確定你在問什麼。你想從幾個字符串中獲得()之間的代碼,或者你想從這個特定的字符串獲取MCO?如果這是最後一種情況,RegEx將是您最好的選擇。 – Pbirkoff 2012-01-06 15:17:17