正则表达式获取单个连接数

我试图过滤掉 inputstring 上的 addressnumber,但问题是我的代码在输入多个数字的字符串时会导致不需要的结果。

是否有可能告诉正则表达式过滤到一个数组或类似的东西来识别原始字符串中是否有多个数字?

String theNumbers = String.Join(String.Empty, Regex.Matches(inputString, @"\d+").OfType<Match>().Select(m => m.Value));

我现在也以不同的方式尝试了它,但是 Regex.Split 在数组中生成空字符串,只是将它们过滤掉对我来说似乎有点麻烦。

String[] extractedNumbersArray = Regex.Split(inputString, @"\D+");


波斯汪
浏览 125回答 1
1回答

温温酱

希望这有帮助(在线):using System;using System.Text.RegularExpressions;using System.Linq;public class Program{&nbsp; &nbsp; public static void Main()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var inputString = "1 2 3";&nbsp; &nbsp; &nbsp; &nbsp; var values = Regex&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Matches(inputString, @"(?<nr>\d+)")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .OfType<Match>()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Select(m => m.Groups["nr"].Value)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .ToArray();&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine("Multipe numbers: " + (values.Length > 1 ? "yep" : "nope"));&nbsp; &nbsp; &nbsp; &nbsp; foreach (var v in values)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(v);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP