[英]C# Distinguish between first and second match
我正在使用正則表達式從包含范圍的字符串中提取數字。 范圍可以是"less than x"
、 "greater than x"
或"between x and y"
:
"10 - 22"
"< 0,5"
"3,50000 - 11,0"
"< 120000"
"> 12"
下面是相關的代碼片段。 在"less than x"
和"greater than x"
的情況下,我使用 RegEx (\d*,\d*)?(\d*)
來捕獲整數/小數。
Low = r.Descr.Contains('>')
? new Quantity {
Value = Convert.ToDecimal(Regex.Match(r.Descr, @"(\d*,\d*)?(\d*)").Value)
}
: r.Descr.Contains('-')
? new Quantity {
Value = Convert.ToDecimal(Regex.Match(r.Descr, @"").Value)
}
: null,
High = r.Descr.Contains('<')
? new Quantity {
Value = Convert.ToDecimal(Regex.Match(r.Descr, @"(\d*,\d*)?(\d*)").Value)
}
: r.Descr.Contains('-')
? new Quantity {
Value = Convert.ToDecimal(Regex.Match(r.Descr, @"").Value)
}
: null,
在"between x and y"
的情況下,我在構建一個提取相關數字的 RegEx 時遇到了困難。 有沒有辦法使用正則表達式來做到這一點?
試試這個表達式:
(\d+,?\d+\s*-\s*\d+,?\d+)|(<\s*\d+,?\d+)|(>\s*\d+,?\d+)
您可以使用
var match = Regex.Match(text, @"(\d+(?:,\d+)?)\s*-\s*(\d+(?:,\d+)*)");
請參閱正則表達式演示。 詳情:
(\d+(?:,\d+)?)
- 捕獲組 1:一位或多位數字后跟可選的逗號和一位或多位數字\s*-\s*
- a -
用零個或多個空格字符括起來(\d+(?:,\d+)*)
- 捕獲組 2:一位或多位數字后跟可選的逗號和一位或多位數字現在, match
在第 0 組中包含3,50000 - 11,0
11,0 substring,並且 rest 兩組包含您的值:
if (match.Success)
{
Console.WriteLine("{0} - first number", match.Groups[1].Value);
Console.WriteLine("{0} - second number", match.Groups[2].Value);
}
請參閱C# 演示:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class Test
{
public static void Main()
{
var text = "some words....3,50000 - 11,0 .... text....";
var match = Regex.Match(text, @"(\d+(?:,\d+)?)\s*-\s*(\d+(?:,\d+)*)");
if (match.Success)
{
Console.WriteLine("{0} - first number", match.Groups[1].Value);
Console.WriteLine("{0} - second number", match.Groups[2].Value);
}
}
}
Output:
3,50000 - first number
11,0 - second number
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.