[英]How to extract number from string c#
I have a string 我有一个弦
"transform(23, 45)"
from this string i have to extract 23 and 45, i did 从这个字符串中,我必须提取23和45,我确实
var xy = "transform(23,45)".Substring("transform(23,45)".indexOf('(') + 1).TrimEnd(')');
var num = xy.Split(',');
I am using c#. 我正在使用c#。 Is there any better method to do this in c#?
在C#中,有没有更好的方法可以做到这一点?
Use a Regular Expression: 使用正则表达式:
string sInput = "transform(23, 45)";
Match match = Regex.Match(sInput, @"(\d)+",
RegexOptions.IgnoreCase);
if (match.Success)
{
foreach (var sVal in match)
// Do something with sVal
}
You can read more on Regular Expressions here . 您可以在此处阅读有关正则表达式的更多信息 。 Use RegExr for training, it helps alot!
使用RegExr进行培训,对您有很大帮助!
Well, a simply regular expression string would be ([0-9]+)
, but you may need to define other expression constraints, eg, what are you doing to handle periods, commas, etc in strings? 好吧,一个简单的正则表达式字符串将是
([0-9]+)
,但是您可能需要定义其他表达式约束,例如,您正在做什么以处理字符串中的句点,逗号等?
var matches = Regex.Matches("transform(23,45)", "([0-9]+)");
foreach (Match match in matches)
{
int value = int.Parse(match.Groups[1].Value);
// Do work.
}
这会做到的
string[] t = "transform(23, 45)".ToLower().Replace("transform(", string.Empty).Replace(")", string.Empty).Split(',');
Use Regex
: 使用正则
Regex
:
var matches = Regex.Matches(inputString, @"(\d+)");
explain: 说明:
\d Matches any decimal digit.
\d+ Matches digits (0-9)
(1 or more times, matching the most amount possible)
and for using: 并用于:
foreach (Match match in matches)
{
var number = match.Groups[1].Value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.