我有一个包含字母字符的字符串,例如:
- 254.69米
- 26.56厘米
- 23.36英寸
- 100.85英尺
我想从上述字符串中删除所有字母字符(单位),这样我就可以调用double.Parse()
方法。
这个应该可以工作:
// add directive at the top
using System.Text.RegularExpressions;
string numberOnly = Regex.Replace(s, "[^0-9.]", "")
您可以使用正则表达式来解决这个问题。将以下引用添加到您的项目中:
using System.Text.RegularExpressions;
之后你可以使用以下内容:
string value = Regex.Replace(<yourString>, "[A-Za-z ]", "");
double parsedValue = double.Parse(value);
假设你只有字母和空格作为单位。
使用LINQ:
using System.Linq;
string input ="57.20000 KG ";
string output = new string(input.Where(c=>(Char.IsDigit(c)||c=='.'||c==',')).ToArray());
你好,另一种解决方案是:
// add directive at the top
using System.Text.RegularExpressions;
string s = "24,99";
string numberOnly = Regex.Replace(s, "[^0-9,-]+", "")
public static string StripAlpha(this string self)
{
return new string( self.Where(c => !Char.IsLetter(c)).ToArray() );
}
public static string StripNonNumeric(this string self)
{
// Use Vlad's LINQ or the Regex Example
return new string(self.Where(c=>(Char.IsDigit(c)||c=='.'||c==',')).ToArray()) ; // See Vlad's
}
var newString = someString.StripAlpha();
var newString2 = someString.StripNonNumeric();
String magnitudeWithUnit = "254.69 meter";
String magnitude = CharMatcher.inRange('a', 'z').or(inRange('A', 'Z')).removeFrom(magnitudeWithUnit);
使用静态导入 CharMatcher.inRange(..)
。你可以去掉结果中的尾部空格。