2

我有一个字符串,它给出了以厘米、米或英寸为单位的测量值。

例如 :

数字可以是 112 厘米、1.12 米、45 英寸或 45 英寸。

我想只提取字符串的数字部分。知道如何使用单位作为分隔符来提取数字吗?

虽然我在这里,但我想忽略单位的情况。

谢谢

4

6 回答 6

2

使用正则表达式可以帮助您:

(?i)(\d+(?:\.\d+)?)(?=c?m|in(?:ch(?:es)?)?)

分手:

 (?i)                 = ignores characters case // specify it in C#, live do not have it
 \d+(\.\d+)?          = supports numbers like 2, 2.25 etc
 (?=c?m|in(ch(es)?)?) = positive lookahead, check units after the number if they are 
                        m, cm,in,inch,inches, it allows otherwise it is not.
 ?:                   = specifies that the group will not capture
 ?                    = specifies the preceding character or group is optional

演示

编辑

示例代码:

MatchCollection mcol = Regex.Matches(sampleStr,@"(?i)(\d+(?:\.\d+)?)(?=c?m|in(?:ch(?:es)?)?)")

foreach(Match m in mcol)
{
    Debug.Print(m.ToString());   // see output window
}
于 2013-08-01T08:14:19.780 回答
2

使用String.Split http://msdn.microsoft.com/en-us/library/tabh47cf.aspx

就像是:

var units = new[] {"cm", "inches", "in", "m"};
var splitnumber = mynumberstring.Split(units, StringSplitOptions.RemoveEmptyEntries);
var number = Convert.ToInt32(splitnumber[0]);
于 2013-08-01T07:21:37.620 回答
2

你可以试试:

string numberMatch = Regex.Match(measurement, @"\d+\.?\d*").Value;

编辑

此外,将其转换为双精度是微不足道的:

double result;
if (double.TryParse(number, out result))
{
    // Yeiiii I've got myself a double ...
}
于 2013-08-01T07:29:44.837 回答
1

我想我会尝试用“”替换每个不是数字或“。”的字符:

//s is the string you need to convert
string tmp=s;
foreach (char c in s.ToCharArray())
            {
                if (!(c >= '0' && c <= '9') && !(c =='.'))
                    tmp = tmp.Replace(c.ToString(), "");
            }
s=tmp;
于 2013-08-01T07:50:41.897 回答
1

尝试使用正则表达式 \d+ 来查找整数。

resultString = Regex.Match(measurementunit , @"\d+").Value;
于 2013-08-01T08:38:15.840 回答
0

是否要求您使用单位作为分隔符?如果没有,您可以使用正则表达式提取数字(请参阅Find and extract a number from a string)。

于 2013-08-01T07:25:18.653 回答