如何从给定的字符串中获取整数值?

时间:2011-04-14 05:38:45

标签: c# java android

我想从字符串中找到整数值。例如,给定一个像“艾哈迈达巴德到甘地纳加尔距离:29公里(约31分钟)”的字符串

我想从给定的字符串中仅获取29,因为我想将这29公里与其他公里进行比较。

3 个答案:

答案 0 :(得分:4)

在C#中,如果在正则表达式中使用组,则可以使用Regex.Match来拉出子串(请注意,这未经过测试...)。在Java中可能有一个类似的机制,但我不知道它在我的头脑中:

var myString = @"Ahmedabad to Gandhinagar Distance:29km(about 31 mins)";
var myRegex = @".*:(\d*)km.*";
var match = Regex.Match(myString, myRegex);

if (match.Success)
{
    // match.Groups contains the match "groups" in the regex (things surrounded by parentheses)
    // match.Groups[0] is the entire match, and in this case match.Groups[1] is the km value
    var km = match.Groups[1].Value;
}

答案 1 :(得分:0)

使用此正则表达式

/[:](\d+)/

你将匹配为29.这是一个rubular link与你的例子。

答案 2 :(得分:0)

在C#中尝试此代码

            string str = "Ahmedabad to Gandhinagar Distance:29km(about 31 mins)";
            str = str.Substring(str.IndexOf(':')+1, str.IndexOf("km") - str.IndexOf(':')-1); ;
            int distance = Convert.ToInt32(str);
相关问题