如何仅从字符串中提取数字 [英] How to extract only numbers from a string

查看:82
本文介绍了如何仅从字符串中提取数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字符串





< Polygon> 
< Vertex x = 9352.7606 y = 8250.6001 z = 505.3871 />
< Vertex x = 9352.7573 y = 8250.6001 z = 505.3844 />
< / 多边形 >







我想得到字符串

  9352  7606   8250  6001   505  3871  
9352 7573 8250 6001 505 3844









如何分割如上所示并存储在新字符串中

解决方案

首先,使用命名空间添加此; 语句:

 使用系统。 Text.RegularExpressions; 



然后,试试这个:

  string  str =  你的字符串在这里; 
MatchCollection matches = Regex.Matches(str, @ \d +(\。\\\ +) ?);
List< string> numbers = new List< string>();
foreach (匹配m 匹配)
{
number。加入(m.Value);
}



如果你不想要一个字符串列表,但需要一个双打列表,试试这个:

  string  str =  你的字符串这里; 
MatchCollection matches = Regex.Matches(str, @ \d +(\。\\\ +) ?);
列表< double> numbers = new List< double>();
foreach (匹配m 匹配)
{
number。添加( Double .Parse(m.Value, new System.Globalization.NumberFormatInfo(){NumberDecimalSeparator = < span class =code-string>
}));
}



我的正则表达式 \d +(\.\ + +)?查找带小数点和无小数点的数字。如果您只想匹配带小数点的数字,请删除括号和问号: \d + \.\d +


访问这里...



http://labs.kaliko.com/2009/09/c-remove-all-non-numeric-characters.html [ ^ ]


< blockquote>使用正则表达式:

 \d + \。\\\ + 

应该这样做......


I am having the following string


<Polygon>
          <Vertex x="9352.7606" y="8250.6001" z="505.3871" />
          <Vertex x="9352.7573" y="8250.6001" z="505.3844" />
          </Polygon>




I want to get the string as

9352.7606    8250.6001     505.3871    
9352.7573    8250.6001     505.3844





How to split as shown above and store in a new string

解决方案

First, add this using namespace; statement:

using System.Text.RegularExpressions;


Then, try this:

string str = "your string here";
MatchCollection matches = Regex.Matches(str, @"\d+(\.\d+)?");
List<string> numbers = new List<string>();
foreach (Match m in matches)
{
    numbers.Add(m.Value);
}


If you don't want a list of strings, but a list of doubles, try this:

string str = "your string here";
MatchCollection matches = Regex.Matches(str, @"\d+(\.\d+)?");
List<double> numbers = new List<double>();
foreach (Match m in matches)
{
    numbers.Add(Double.Parse(m.Value, new System.Globalization.NumberFormatInfo() { NumberDecimalSeparator = "." }));
}


My regular expression \d+(\.\d+)? looks for numbers with and without decimal point. If you only want to match numbers with a decimal point, remove the parentheses and the question mark: \d+\.\d+


visit here...

http://labs.kaliko.com/2009/09/c-remove-all-non-numeric-characters.html[^]


Use a regular expression:

\d+\.\d+

Should do it...


这篇关于如何仅从字符串中提取数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆