Doo*_*ake 10 javascript c# integer parseint
我想知道是否有人把某些东西放在一起或者已经看到了与C#的JavaScript parseInt相当的东西.
具体来说,我希望采取如下字符串:
123abc4567890
Run Code Online (Sandbox Code Playgroud)
并仅返回第一个有效整数
123
Run Code Online (Sandbox Code Playgroud)
我有一个我用过的静态方法只返回数字:
public static int ParseInteger( object oItem )
{
string sItem = oItem.ToString();
sItem = Regex.Replace( sItem, @"([^\d])*", "" );
int iItem = 0;
Int32.TryParse( sItem, out iItem );
return iItem;
}
Run Code Online (Sandbox Code Playgroud)
以上将采取:
ParseInteger( "123abc4567890" );
Run Code Online (Sandbox Code Playgroud)
并把我还给我
1234567890
Run Code Online (Sandbox Code Playgroud)
我不确定是否可以使用正则表达式,或者是否有更好的方法来从字符串中获取第一个整数.
lep*_*pie 17
你很亲密
你可能只想要:
foreach (Match match in Regex.Matches(input, @"^\d+"))
{
return int.Parse(match.Value);
}
Run Code Online (Sandbox Code Playgroud)
这是一个完整的例子.如果你没有给它一个有效的字符串,它将抛出一个异常 - 你可以通过不明确地抛出异常ParseInteger并int.TryParse改为使用来改变这种行为.
请注意,它也允许使用前导符号,但不允许使用前导符号.(再次,容易改变.)
另请注意,虽然我有三个成功案例的测试用例,但我没有任何失败的测试用例.
最后,它不匹配"abc123def".如果需要,请从正则表达式中删除^.
using System;
using System.Text;
using System.Text.RegularExpressions;
class Test
{
static void Main(string[] args)
{
Check("1234abc", 1234);
Check("-12", -12);
Check("123abc456", 123);
}
static void Check(string text, int expected)
{
int actual = ParseInteger(text);
if (actual != expected)
{
Console.WriteLine("Expected {0}; got {1}", expected, actual);
}
}
private static readonly Regex LeadingInteger = new Regex(@"^(-?\d+)");
static int ParseInteger(string item)
{
Match match = LeadingInteger.Match(item);
if (!match.Success)
{
throw new ArgumentException("Not an integer");
}
return int.Parse(match.Value);
}
}
Run Code Online (Sandbox Code Playgroud)