查找所有数字的字符串 [英] Finding all numbers in a string

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

问题描述

我的应用程序的一部分具有供用户输入文本TextBox控件的区域。他们将进入文本和数字到文本框中。当用户按下一个按钮,文本框输出其文本字符串,找到字符串中的所有数字,由1.14乘以他们,吐出来的是键入文本到pretty小文本块。

Part of my app has an area where users enter text into a textBox control. They will be entering both text AND numbers into the textBox. When the user pushes a button, the textBox outputs its text into a string, finds all numbers in the string, multiplies them by 1.14, and spits out the typed text into a pretty little textBlock.

基本上,我想要做的就是发现所有的数字字符串中的,1.14相乘,然后将它们放回字符串。

Basically, what I want to do is find all the numbers in a string, multiply them by 1.14, and insert them back into the string.

起初,我以为这可能是一个简单的问题:刚<一个href=\"http://www.bing.com/search?setmkt=en-US&q=Finding+all+numbers+in+a+string+c%23&first=1&FORM=PERE\"相对=nofollow>兵称号并看看会发生什么吧。

At first, I thought this may be an easy question: just Bing the title and see what comes up.

但现在紫色环节两页后,我开始觉得我不能用我自己的,正则表达式的非常轻薄的知识解决这个问题。

But after two pages of now-purple links, I'm starting to think I can't solve this question with my own, very skimpy knowledge of Regex.

不过,我确实发现有用的链接的集合爽朗:

However, I did find a hearty collection of helpful links:

  • This article from DotNetPerls
  • This code snippet at Snipplr
  • This question on MSDN
  • This answer on StackOverflow
  • This article from AssociatedContent
  • This question on MSDN
  • This article on Java2s.com

请注意:的几个这些文章的接近做我想做的事情,从字符串获取的数字,但他们没有的查找字符串中的所有数字

Please note: A few of these articles come close to doing what I want to do, by fetching the numbers from the strings, but none of them find all the numbers in the string.

示例:
用户输入以下字符串文本框:鸡肉,冰淇淋,567,奶酪另外,140和1337

Example: A user enters the following string into the textBox: "Chicken, ice cream, 567, cheese! Also, 140 and 1337."

该计划将然后吐出这到文本块:鸡肉,冰淇淋,646.38,奶酪此外,159.6和1524.18

The program would then spit out this into the textBlock: "Chicken, ice cream, 646.38, cheese! Also, 159.6 and 1524.18."

推荐答案

您可以使用数字匹配的正前pression,并使用 Regex.Replace 方法。我不知道你在数字一词包括但这种将取代所有非负整数,例如像 42 123456

You can use a regular expression that matches the numbers, and use the Regex.Replace method. I'm not sure what you include in the term "numbers", but this will replace all non-negative integers, like for example 42 and 123456:

str = Regex.Replace(
  str,
  @"\d+",
  m => (Double.Parse(m.Groups[0].Value) * 1.14).ToString()
);

如果你需要数字的其他一些定义,例如科学记数法,你需要一个更elaboarete经常EX pression,但原理是一样的。

If you need some other definition of "numbers", for example scientific notation, you need a more elaboarete regular expression, but the principle is the same.

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

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