I have a string containg alphabetic characters, for example:
我有一个包含字母字符的字符串,例如:
- 254.69 meters
- 254.69米
- 26.56 cm
- 26.56厘米
- 23.36 inches
- 23.36英寸
- 100.85 ft
- 100.85英尺
I want to remove all the alphabetic characters (units) from the above mentioned strings so that I can call the double.Parse() method.
我想从上面提到的字符串中删除所有字母字符(单位),以便我可以调用double.Parse()方法。
4 个解决方案
#1
81
This should work:
这应该工作:
Regex.Replace(s, "[^0-9.]", "")
#2
19
You should be able to solve this using Regex. Add the following reference to your project:
您应该能够使用Regex解决此问题。将以下引用添加到项目中:
using System.Text.RegularExpressions;
after that you can use the following:
之后,您可以使用以下内容:
string value = Regex.Replace(<yourString>, "[A-Za-z ]", "");
double parsedValue = double.Parse(value);
Assuming you have only alphabetic characters and space as units.
假设您只有字母字符和空格作为单位。
#3
3
Using LINQ:
使用LINQ:
using System.Linq;
string input ="57.20000 KG ";
string output = new string(input.Where(c=>(Char.IsDigit(c)||c=='.'||c==',')).ToArray());
#4
0
Use CharMatcher API from Google's Guava library:
使用Google的Guava库中的CharMatcher API:
String magnitudeWithUnit = "254.69 meter"; String magnitude = CharMatcher.inRange('a', 'z').or(inRange('A', 'Z')).removeFrom(magnitudeWithUnit);
String magnitudeWithUnit =“254.69米”; String magnitude = CharMatcher.inRange('a','z')。或(inRange('A','Z'))。removeFrom(magnitudeWithUnit);
Do static-import CharMatcher.inRange(..). You can trim the results for trailing space.
执行静态导入CharMatcher.inRange(..)。您可以修剪尾随空格的结果。
#1
81
This should work:
这应该工作:
Regex.Replace(s, "[^0-9.]", "")
#2
19
You should be able to solve this using Regex. Add the following reference to your project:
您应该能够使用Regex解决此问题。将以下引用添加到项目中:
using System.Text.RegularExpressions;
after that you can use the following:
之后,您可以使用以下内容:
string value = Regex.Replace(<yourString>, "[A-Za-z ]", "");
double parsedValue = double.Parse(value);
Assuming you have only alphabetic characters and space as units.
假设您只有字母字符和空格作为单位。
#3
3
Using LINQ:
使用LINQ:
using System.Linq;
string input ="57.20000 KG ";
string output = new string(input.Where(c=>(Char.IsDigit(c)||c=='.'||c==',')).ToArray());
#4
0
Use CharMatcher API from Google's Guava library:
使用Google的Guava库中的CharMatcher API:
String magnitudeWithUnit = "254.69 meter"; String magnitude = CharMatcher.inRange('a', 'z').or(inRange('A', 'Z')).removeFrom(magnitudeWithUnit);
String magnitudeWithUnit =“254.69米”; String magnitude = CharMatcher.inRange('a','z')。或(inRange('A','Z'))。removeFrom(magnitudeWithUnit);
Do static-import CharMatcher.inRange(..). You can trim the results for trailing space.
执行静态导入CharMatcher.inRange(..)。您可以修剪尾随空格的结果。