从混合字母数字字符串中提取仅数字

3
我想使用正则表达式从一个包含混合字母的句子中提取一系列数字。
例如:
"Please buy 40 kg of apples for 1350$ each"                  --> "40|1350"
"Please call 8 0 0 4 3 2 1 2 4 3 from 17:00 till 22:00"      --> "8004321243|1700|2200"
"I would like to bid 50 euro on 20 black and pair of spades" --> "50|20"

只有数字能被提取出来,任何在其间的单词都会被截断并用|分隔。如果数字之间有非单词字符分隔,它们将被视为第2个示例中相同的数字。

3个回答

1
使用Regex.Replace(s, @"\W+", "")删除所有非单词字符,然后使用简单的\d+模式提取所有数字块:
var res = Regex.Matches(Regex.Replace(s, @"\W+", ""), @"\d+")
       .Cast<Match>()
       .Select(m=>m.Value)
       .ToList();

看一下 C#演示

0

你可以先尝试搜索数字后跟数字加非单词字符,并在清理正则表达式匹配后进行消毒:

var str = "Please call 8 0 0 4 3 2 1 2 4 3 from 17:00 till 22:00";

var regex1 = new Regex(@"([\d]+[\d\W]*)");
var regex2 = new Regex(@"([\W]+)");    

foreach (var match in regex1.Matches(str).Cast<Match>())
{
    var val = match.Groups[1].Value;    

    foreach (var nonWordMatch in regex2.Matches(val).Cast<Match>())
    {
        val = val.Replace(nonWordMatch.Value, "");
    }

    var number = Int64.Parse(val);
    Console.WriteLine(">> num " + number);
}

0
StringBuilder number = new StringBuilder();
List<string> test = new List<string>();

foreach (char c in s)
    {
        if (Char.IsDigit(c)) {
           number.append(c);
        }
        else if (c == ' ' || c == ':') {
          //donnothing
        }
        else {
           if (number.Length > 0) {
           test.add(number.ToString());
           number.Clear();
           }
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接