[英]C# regular expression match
18.君。 7 noči od 515,00 歐元
在這里,我想用正則表達式得到 515,00。
Regex regularExpr = new Regex(@rule.RegularExpression,
RegexOptions.Compiled | RegexOptions.Multiline |
RegexOptions.IgnoreCase | RegexOptions.Singleline |
RegexOptions.IgnorePatternWhitespace);
tagValue.Value = "18.jun. 7 noči od 515,00 EUR";
Match match = regularExpr.Match(tagValue.Value);
object value = match.Groups[2].Value;
正則表達式是: \d+((.\d+)+(,\d+)?)?
但我總是得到一個空字符串(“”)。 如果我在 Expresso 中嘗試這個正則表達式,我會得到一個包含 3 個值的數組,第三個是 515,00。
我的 C# 代碼有什么問題,我得到一個空字符串?
您的正則表達式匹配18
(因為小數部分是可選的),並且match.Groups[2]
指的是第二個捕獲括號(.\d+)
應該正確讀取(\.\d+)
並且沒有參與匹配,因此返回空字符串。
您需要更正您的正則表達式並迭代結果:
StringCollection resultList = new StringCollection();
Regex regexObj = new Regex(@"\d+(?:[.,]\d+)?");
Match matchResult = regexObj.Match(subjectString);
while (matchResult.Success) {
resultList.Add(matchResult.Value);
matchResult = matchResult.NextMatch();
}
resultList[2]
然后將包含您的匹配項。
確保在創建正則表達式時正確地轉義了所有內容。
Regex re = new Regex("\d+((.\d+)+(,\d+)?)?")
與
Regex re = new Regex(@"\d+((.\d+)+(,\d+)?)?")
你可能想要第二個。
我懷疑你在 Expresso 中得到的結果是這樣的:
string s = "18.jun. 7 noči od 515,00 EUR";
Regex r = new Regex(@"\d+((.\d+)+(,\d+)?)?");
foreach (Match m in r.Matches(s))
{
Console.WriteLine(m.Value);
}
換句話說,您看到的不是第二個捕獲組的內容,而是第三個match 。 這段代碼更清楚地顯示了它:
Console.WriteLine("{0,10} {1,10} {2,10} {3,10}",
@"Group 0", @"Group 1", @"Groups 2", @"Group 3");
Regex r = new Regex(@"\d+((.\d+)+(,\d+)?)?");
foreach (Match m in r.Matches(s))
{
Console.WriteLine("{0,10} {1,10} {2,10} {3,10}",
m.Groups[0].Value, m.Groups[1].Value, m.Groups[2].Value, m.Groups[3].Value);
}
output:
Group 0 Group 1 Group 2 Group 3
18
7
515,00 ,00 ,00
到正則表達式本身。 如果您只想匹配價格而不匹配其他數字,則需要更具體。 例如,如果您知道,00
部分將始終存在,則可以使用此正則表達式:
@"(?n)\b\d+(\.\d+)*(,\d+)\b"
(?n)
是ExplicitCapture
選項的內聯形式,它將這兩個捕獲組轉換為非捕獲組。 在您指定的 RegexOptions中,唯一有效的是Compiled
,它稍微加快了正則表達式的匹配,但會減慢其構造並占用 memory。 \b
是單詞邊界。
看起來你在構造它們時盲目地將所有這些修飾符應用於每個正則表達式,這不是一個好主意。 如果特定的正則表達式需要某個修飾符,您應該嘗試在正則表達式本身中使用內聯修飾符指定它,就像我對(?n)
所做的那樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.