Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

c# - Finding all numbers in a string

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.

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.

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:

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.

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()
);

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...