在我当前的项目中,我必须大量使用子字符串,我想知道是否有更简单的方法可以从字符串中取出数字。
示例:我有一个这样的字符串:12 text text 7 text
我希望能够获得第一个号码组或第二个号码组。因此,如果我要求数字集 1,我将得到 12 作为回报,如果我要求数字集 2,我将得到 7 作为回报。
谢谢!
这将从字符串创建一个整数数组:
using System.Linq;
using System.Text.RegularExpressions;
class Program {
static void Main() {
string text = "12 text text 7 text";
int[] numbers = (from Match m in Regex.Matches(text, @"\d+") select int.Parse(m.Value)).ToArray();
}
}
看起来很适合Regex
.
基本的正则表达式将\d+
匹配(一个或多个数字)。
您将遍历从Matches
返回的集合Regex.Matches
并依次解析每个返回的匹配项。
var matches = Regex.Matches(input, "\d+");
foreach(var match in matches)
{
myIntList.Add(int.Parse(match.Value));
}
尝试使用正则表达式,您可以匹配[0-9]+
将匹配字符串中任何数字的匹配。使用这个正则表达式的 C# 代码大致如下:
Match match = Regex.Match(input, "[0-9]+", RegexOptions.IgnoreCase);
// Here we check the Match instance.
if (match.Success)
{
// here you get the first match
string value = match.Groups[1].Value;
}
当然,您仍然必须解析返回的字符串。
你可以使用正则表达式:
Regex regex = new Regex(@"^[0-9]+$");
您可以使用 string.Split 将字符串分成几部分,然后使用应用 int.TryParse 的 foreach 遍历列表,如下所示:
string test = "12 text text 7 text";
var numbers = new List<int>();
int i;
foreach (string s in test.Split(' '))
{
if (int.TryParse(s, out i)) numbers.Add(i);
}
现在 numbers 有有效值的列表