[英]Is there an equivalent to JavaScript parseInt in C#?
I was wondering if anyone had put together something or had seen something equivalent to the JavaScript parseInt for C#. 我想知道是否有人把一些东西放在一起或者已经看到了与C#的JavaScript parseInt相当的东西。
Specifically, i'm looking to take a string like: 具体来说,我希望采取如下字符串:
123abc4567890
and return only the first valid integer 并仅返回第一个有效整数
123
I have a static method I've used that will return only the numbers: 我有一个我用过的静态方法只返回数字:
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;
}
The above would take: 以上将采取:
ParseInteger( "123abc4567890" );
and give me back 并把我还给我
1234567890
I'm not sure if it's possible to do with a regular expression, or if there is a better method to grab just the first integer from the string. 我不确定是否可以使用正则表达式,或者是否有更好的方法来从字符串中获取第一个整数。
You are close. 你很亲密
You probably just want: 你可能只想要:
foreach (Match match in Regex.Matches(input, @"^\d+"))
{
return int.Parse(match.Value);
}
Here's a complete example. 这是一个完整的例子。 It will throw an exception if you don't give it a valid string - you can change this behaviour by not explicitly throwing an exception in ParseInteger
, and using int.TryParse
instead. 如果你没有给它一个有效的字符串,它将抛出一个异常 - 你可以通过不在ParseInteger
显式抛出异常并使用int.TryParse
来改变这种行为。
Note that it allows a leading - sign as well, but not a leading +. 请注意,它也允许使用前导符号,但不允许使用前导符号。 (Again, easy to change.) (再次,容易改变。)
Also note that although I've got three test cases for success situations, I haven't got any test cases for failure. 另请注意,虽然我有三个成功案例的测试用例,但我没有任何失败的测试用例。
Finally, it won't match "abc123def". 最后,它不匹配“abc123def”。 If you want it to, remove the ^ from the regex. 如果需要,请从正则表达式中删除^。
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);
}
}
A slight change to Jon Skeet's excellent solution is in order. Jon Skeet的优秀解决方案略有改变。
I would change the regex to (as mentioned by Jon): 我会将正则表达式更改为(如Jon所述):
@"^([^\\d]+)?(+|-)?\\d+"
This allows for the case of leading characters ahead of the first occurrence of a digit 这允许在第一次出现数字之前引导字符的情况
(eg, asb12354
-> 12354
) and both signed integer cases (eg +
or -
) (例如, asb12354
- > 12354
)和两个有符号整数的情况(例如+
或-
)
public static int ParseInteger( object oItem )
{
int iItem = 0;
if (oItem != null) {
Int32.TryParse( Regex.Match( oItem.ToString(), @"\d+" ).Value, out iItem );
}
return iItem;
}
int nr = Int32.Parse(yourstring);
You could use this RegEx ("\\A\\d+") to find numbers at the beginning of a string. 您可以使用此RegEx(“\\ A \\ d +”)在字符串的开头查找数字。
You can then use int.Parse() to convert that string into an actual integer. 然后,您可以使用int.Parse()将该字符串转换为实际的整数。
You DON'T have to write your own int parse function!!!! 你不必编写自己的int解析函数!!!!
I know this thread is pretty old. 我知道这个帖子很老了。 but there are some simple way to do this: 但有一些简单的方法可以做到这一点:
int.Parse(urString);
use short.Parse(urString); //if you want a short
Or: //use those depend on your situation: 或者://根据您的情况使用这些:
Convert.ToInt16();
Convert.ToInt32();
Convert.ToInt64();
NOTE: 注意:
I am answering your Topic Question "Is there an equivalent to JavaScript parseInt in C#?", just give you some idea, NOT write your code for you. 我正在回答您的主题问题“在C#中是否存在与JavaScript parseInt相同的内容?”,只是给您一些想法,而不是为您编写代码。 You need to first do a filtering on 'Alphabetical Characters', you can do it with Regular Expression or a simple string.Replace, or up to you. 您需要先对“字母字符”进行过滤,您可以使用正则表达式或简单的字符串。替换,或由您决定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.