如何从以下字符串中获取数字:
###E[shouldbesomenumber][space or endofline]
这里的[]仅用于真实字符串中不存在的插图。
我使用的是.net 2.0。
谢谢。
最佳答案
我建议你使用正则表达式或字符串操作来隔离只是数字部分,然后调用int.Parse
、int.TryParse
、decimal.Parse
、decimal.TryParse
等,具体取决于您需要解析的数字类型。
正则表达式可能类似于:
@"###E(-?\d+) ?$";
当然,您需要将其更改为非整数。示例代码:
using System;
using System.Text.RegularExpressions;
class Test
{
static void Main(string[] arg)
{
Regex regex = new Regex(@"###E(-?\d+) ?$");
string text = "###E123 ";
Match match = regex.Match(text);
if (match.Success)
{
string group = match.Groups[1].Value;
int parsed = int.Parse(group);
Console.WriteLine(parsed);
}
}
}
请注意,如果数字超出 int
范围,这仍然可能会失败。 (使用 int.TryParse
的另一个原因...)
关于c# - 从字符串中获取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7702451/