![](/img/trans.png)
[英]How can I get my regex route attribute to match an empty value in addition to validating a user supplied value?
[英]How can i find and get the value of a match with regex?
我有以下模式>4.66<
我想在一個字符串中找到。 以下代碼用於查找模式並為med提供double值:
string data = File.ReadAllText("test.txt");
string pattern = "^>\\d.\\d<";
if (Regex.IsMatch(data, pattern))
{
MatchCollection mc = Regex.Matches(data, pattern);
foreach (Match m in mc)
{
double value = double.Parse(m.Value.Substring(1, m.Value.Length - 1));
string foo = "" + 2;
}
}
我認為我的模式是錯誤的,因為我似乎找不到> 4.66 <我在源頭看到它就在那里:D
使用以下正則表達式:
(?<=>)\d+\.\d+(?=<)
稍微簡化的代碼:
string data = File.ReadAllText("test.txt");
MatchCollection mc = Regex.Matches(data, @"(?<=>)\d+\.\d+(?=<)");
foreach (Match m in mc)
{
double value = double.Parse(m.Value, CultureInfo.InvariantCulture);
}
您不需要調用IsMatch
方法,因為如果沒有匹配, Matches
將只返回空集合。
主要的是,你缺少量詞 。 使用\\d
您正好匹配1位數。 如果要匹配更多它們,則需要定義它。
+
是重復前一項1或更多的量詞。
要從字面上匹配一個點,它需要被轉義,因為它是正則表達式中的特殊字符 。
使用逐字字符串以避免雙重轉義
僅使用外觀 斷言或使用捕獲組匹配您需要的內容( 如Ulugbek所述 )
我從你的模式中刪除了^
,因為它匹配字符串的開頭,你寫了你想在字符串中找到。
所以我們最終得到:
string pattern = @">(\d.\d+)<";
MatchCollection mc = Regex.Matches(data, pattern);
foreach (Match m in mc)
{
double value = double.Parse(m.groups[1]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.