我需要在文本行字段中找到数字/双精度并返回其值。 文本行可以是这样的:" asdajkj asdk asdkj 10.1 asdasd" 所以我想要从这一行返回10.1的值。
答案 0 :(得分:3)
试试这个: -
string yourString = "asdajkj asdk asdkj 10.1 asdasd";
var resultString = Regex.Match(yourString, @"-?\d+(\.?\d+)?").Value;
更多: -
string yourString = "asdajkj asdk asdkj 10.1 asdasd";
string firstOccurance = Regex.Match(yourString, @"-?\d+(\.?\d+)?").Value;
Console.WriteLine(firstOccurance);
/* Multiple Occurance */
string yourString_2 = "asdajkj 10 asdk 23.26 asdkj 10.1 asdasd 15 ";
MatchCollection results = Regex.Matches(yourString_2, @"-?\d+(\.?\d+)?");
foreach (Match item in results)
{
Console.WriteLine(item.Value);
}
答案 1 :(得分:0)
string input = "sdajkj asdk asdkj 10.1 asdasd";
// Split on one or more non-digit characters.
string[] numbers = Regex.Split(input, @"\D+");
答案 2 :(得分:0)
从字符串中获取第一个数字。
Regex.Match(yourString, @"(?<=^\D*)\d+(?:\.\d+)?").Value
答案 3 :(得分:0)
你不需要Regex来做到这一点:
string input = "asdajkj asdk asdkj 10.1 asdasd";
string res = new string(input.SkipWhile(c => !Char.IsDigit(c)).TakeWhile(c => Char.IsDigit(c) || c == '.').ToArray());
Console.WriteLine(res); // 10.1