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

本文关键字:获取 整数 字符串 | 更新日期: 2023-09-27 17:50:00

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

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

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

在c#中,你可以使用正则表达式。如果您在正则表达式中使用组,则匹配提取子字符串(注意这没有经过测试…)。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;
}

使用这个正则表达式

/[:]('d+)/

,匹配值为29。

在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);