C# 从字符串中获取特定的数字
在我目前的项目中,我必须大量使用子字符串,我想知道是否有更简单的方法从字符串中提取数字 例如: 我有这样一个字符串: 12文本文本7文本 我想可以拿到第一组号码或第二组号码。 所以如果我要数字集1,我会得到12作为回报,如果我要数字集2,我会得到7作为回报C# 从字符串中获取特定的数字,c#,string,split,C#,String,Split,在我目前的项目中,我必须大量使用子字符串,我想知道是否有更简单的方法从字符串中提取数字 例如: 我有这样一个字符串: 12文本文本7文本 我想可以拿到第一组号码或第二组号码。 所以如果我要数字集1,我会得到12作为回报,如果我要数字集2,我会得到7作为回报 谢谢 看起来很适合你 基本正则表达式应该是\d+,以匹配(一个或多个数字) 您将遍历从Regex.Matches返回的Matches集合,并依次解析每个返回的匹配项 var matches = Regex.Matches(input, "\d
谢谢 看起来很适合你 基本正则表达式应该是
\d+
,以匹配(一个或多个数字)
您将遍历从Regex.Matches
返回的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]+$");
这将从字符串创建一个整数数组:
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();
}
}
您可以使用string.split将字符串拆分为多个部分,然后使用foreach应用int.TryParse遍历列表,如下所示:
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);
}
string test=“12 text 7 text”;
变量编号=新列表();
int i;
foreach(test.Split(“”)中的字符串s)
{
if(int.TryParse(s,out i))编号。添加(i);
}
现在数字有了有效值列表您假设不允许使用前导的
0
s。谢谢,这正是我需要的!:顺便说一句,对否决票表示抱歉,我不知道我不能投票,因为我是新注册的。@TobiasLindberg:很高兴这有帮助,在这种情况下,你可以撤销否决票meybe:)?对不起,这只是客户方面的事,它实际上没有否决你。再次感谢!那我很想知道为什么有人否决了答案。不管怎样,欢迎您:)@Jack:您是否尝试过错误消息所建议的方法,即添加对System.Core.dll的引用(如果您复制了示例,我想使用System.Linq
),您好,谢谢。如第一句所述,它应该是TryParse。我已经改正了。