我正在爬取一些网站内容,它看起来像这样:"公司股票 Rs. 7100"。
现在,我想从这个字符串中提取数字值。我尝试了分割但是我的正则表达式总是出现错误。
请告诉我如何获取这个值。
请告诉我如何获取这个值。
使用:
var result = Regex.Match(input, @"\d+").Value;
如果你想在字符串中查找最后一个“实体”的数字,你应该使用这个正则表达式:
\d+$
如果你想匹配字符串中的最后一个数字,可以使用:
\d+(?!\D*\d)
int val = int.Parse(Regex.Match(input, @"\d+", RegexOptions.RightToLeft).Value);
我一直喜欢LINQ
:
var theNumber = theString.Where(x => char.IsNumber(x));
尽管 正则表达式
听起来像是本地选择...
1 a 2
这样的字符串怎么处理? - Kirill Polishchuk12
。我写的是Regex
是本地选择。我只是展示了另一种使用LINQ
的方法。(如果你的意思是这样,我会使用Regex
...) - gdoronnew string(theString)
来将它转换成字符串。 - gdorontheString.Where(char.IsNumber);
。 - aloisdg此代码将返回字符串末尾的整数。如果字符串中的某个位置有数字,则此方法比正则表达式更有效。
public int getLastInt(string line)
{
int offset = line.Length;
for (int i = line.Length - 1; i >= 0; i--)
{
char c = line[i];
if (char.IsDigit(c))
{
offset--;
}
else
{
if (offset == line.Length)
{
// No int at the end
return -1;
}
return int.Parse(line.Substring(offset));
}
}
return int.Parse(line.Substring(offset));
}
这是我的回答...它使用C#将数字和字符串分开...
static void Main(string[] args)
{
String details = "XSD34AB67";
string numeric = "";
string nonnumeric = "";
char[] mychar = details.ToCharArray();
foreach (char ch in mychar)
{
if (char.IsDigit(ch))
{
numeric = numeric + ch.ToString();
}
else
{
nonnumeric = nonnumeric + ch.ToString();
}
}
int i = Convert.ToInt32(numeric);
Console.WriteLine(numeric);
Console.WriteLine(nonnumeric);
Console.ReadLine();
}
}
}
str.Substring(str.LastIndexOf(" ") + 1)
您可以使用\d+
来匹配第一个数字的出现:
string num = Regex.Match(input, @"\d+").Value;