我需要找到并提取字符串中包含的数字。
例如,从以下字符串中:
string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
我该怎么做?
\d+
是匹配整数的正则表达式。
//System.Text.RegularExpressions.Regex
resultString = Regex.Match(subjectString, @"\d+").Value;
返回一个字符串,其中包含subjectString
中的第一次出现的数字。
然后使用Int32.Parse(resultString)
将给您这个数字。
Regex.Match(subjectString, @"-?\d+").Value
。 - Jon List以下是我如何清洗电话号码,仅保留数字:
string numericPhone = new String(phone.Where(Char.IsDigit).ToArray());
string numericPhone =new String(phone.Where(Char.IsDigit).ToArray());
- DamithConcat
替换字符串构造:string.Concat(phone.Where(Char.IsDigit).ToArray())
。 - zcoop98遍历字符串并使用Char.IsDigit
string a = "str123";
string b = string.Empty;
int val;
for (int i=0; i< a.Length; i++)
{
if (Char.IsDigit(a[i]))
b += a[i];
}
if (b.Length>0)
val = int.Parse(b);
b == "System.Linq.Enumerable.."
。正确的(甚至更简单的)写法应该是 b = String.Join("", a.Where(char.IsDigit))
。 - BlueRaja - Danny Pflughoeftnew string(char[])
构造函数从char数组创建一个字符串。 - Thomas使用正则表达式...
Regex re = new Regex(@"\d+");
Match m = re.Match("test 66");
if (m.Success)
{
Console.WriteLine(string.Format("RegEx found " + m.Value + " at position " + m.Index.ToString()));
}
else
{
Console.WriteLine("You didn't enter a string containing a number!");
}
我用的方法可以获取没有任何标点符号的电话号码...
var phone = "(787) 763-6511";
string.Join("", phone.ToCharArray().Where(Char.IsDigit));
// result: 7877636511
Regex.Split 可以从字符串中提取数字。您可以获得在字符串中找到的所有数字。
string input = "There are 4 numbers in this string: 40, 30, and 10.";
// Split on one or more non-digit characters.
string[] numbers = Regex.Split(input, @"\D+");
foreach (string value in numbers)
{
if (!string.IsNullOrEmpty(value))
{
int i = int.Parse(value);
Console.WriteLine("Number: {0}", i);
}
}
输出:
数字:4 数字:40 数字:30 数字:10
如果这个数有小数点,可以使用以下方法:
using System;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
//Your code goes here
Console.WriteLine(Regex.Match("anything 876.8 anything", @"\d+\.*\d*").Value);
Console.WriteLine(Regex.Match("anything 876 anything", @"\d+\.*\d*").Value);
Console.WriteLine(Regex.Match("$876435", @"\d+\.*\d*").Value);
Console.WriteLine(Regex.Match("$876.435", @"\d+\.*\d*").Value);
}
}
}
结果:
"anything 876.8 anything" ==> 876.8
"anything 876 anything" ==> 876
"$876435" ==> 876435
"$876.435" ==> 876.435
Linq
的版本:string s = "123iuow45ss";
var getNumbers = (from t in s
where char.IsDigit(t)
select t).ToArray();
Console.WriteLine(new string(getNumbers));
"123iuow45ss".AsEnumerable().Where(char.IsDigit)
就可以了? - Ilya Ivanovfrom t .. select t
的冗余,但无论如何,干杯。 - Ilya Ivanov使用正则表达式的另一个简单解决方案 你应该需要使用这个
using System.Text.RegularExpressions;
代码如下
string var = "Hello3453232wor705Ld";
string mystr = Regex.Replace(var, @"\d", "");
string mynumber = Regex.Replace(var, @"\D", "");
Console.WriteLine(mystr);
Console.WriteLine(mynumber);
你也可以尝试这个方法
string.Join(null,System.Text.RegularExpressions.Regex.Split(expr, "[^\\d]"));
1.5
?指数记数法,如1.5E45
? - Tim Pietzcker