【发布时间】:2012-05-05 18:44:54
【问题描述】:
在我当前的项目中,我必须大量使用子字符串,我想知道是否有更简单的方法可以从字符串中取出数字。
示例: 我有一个这样的字符串: 12文字文字7文字
我希望能够获得第一个号码组或第二个号码组。 因此,如果我要求数字集 1,我将得到 12 作为回报,如果我要求数字集 2,我将得到 7 作为回报。
谢谢!
【问题讨论】:
在我当前的项目中,我必须大量使用子字符串,我想知道是否有更简单的方法可以从字符串中取出数字。
示例: 我有一个这样的字符串: 12文字文字7文字
我希望能够获得第一个号码组或第二个号码组。 因此,如果我要求数字集 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();
}
}
【讨论】:
using System.Linq 在那里)
尝试使用正则表达式,您可以匹配[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。
基本正则表达式将是\d+ 以匹配(一位或多位数字)。
您将遍历从Regex.Matches 返回的Matches 集合,并依次解析每个返回的匹配项。
var matches = Regex.Matches(input, "\d+");
foreach(var match in matches)
{
myIntList.Add(int.Parse(match.Value));
}
【讨论】:
你可以使用正则表达式:
Regex regex = new Regex(@"^[0-9]+$");
【讨论】:
0s 是不允许的。
您可以使用 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 有有效值列表
【讨论】: