給定格式固定的字串 "29℃~20℃",需提取最高溫 29。
模式 @"(\d+)℃~(\d+)℃" 解析:
(\d+):捕獲組 1,匹配一位或多位數字(最高溫)。℃~:字面匹配分隔符。(\d+):捕獲組 2,匹配最低溫。℃:結束標記。string pattern = @"(\d+)℃~(\d+)℃";
string input = "29℃~20℃";
Match m = Regex.Match(input, pattern);
if (m.Success)
{
string highTemp = m.Groups[1].Value; // "29"
string lowTemp = m.Groups[2].Value; // "20"
Console.WriteLine($"最高溫: {highTemp}℃, 最低溫: {lowTemp}℃");
}
int high = int.Parse(m.Groups[1].Value);
int low = int.Parse(m.Groups[2].Value);
@"\s*(\d+)\s*℃\s*~\s*(\d+)\s*℃"。Groups[0] 為整個匹配字串,Groups[1] 才是第一個捕獲組。