views:

81

answers:

5
string sentence = "X10 cats, Y20 dogs, 40 fish and 1 programmer.";

 string[] digits = Regex.Split (sentence, @"\D+");

for this code i get values in digits array like this 10,20,40,1

string sentence = "X10.4 cats, Y20.5 dogs, 40 fish and 1 programmer.";

 string[] digits = Regex.Split (sentence, @"\D+");

for this code i get values in digits array like this 10,4,20,5,40,1

but i like to get like this 10.4,20.5,40,1 in decimal numbers how can i do this.

A: 

If you have Linq:

stringArray.Select(s=>decimal.Parse(s));

A foreach would also work. You may need to check that each string is actually a number (.Parse does not throw en exception).

cofiem
how do i get s value
ratty
s is the in-scope variable for the Linq query. It is similar to saying foreach(string s in stringArray).
Ryan Bennett
+2  A: 

try

Regex.Split (sentence, @"[^0-9\.]+")
Michael Pakhantsov
This would also give you a false positive on a value of 10.1.1.4.
Joel Etherton
Doesn't the caret (^) negate this?
Daren Thomas
@Daren Thomas, \D equal [^0-9]
Michael Pakhantsov
@Joel Etherton, yes, it will match also string like '10.1.1.4' and even single dot.
Michael Pakhantsov
@Daren Thomas, You're *splitting* the sentence at a series of non-numeric characters, leaving only numerics behind.
strager
@strager, yeah, I figured that out too. I guess I still think in Regex matches as opposed to splitting on them...
Daren Thomas
+1  A: 

Check the syntax lexers for most programming languages for a regex for decimals. Match that regex to the string, finding all matches.

Daren Thomas
A: 

You'll need to allow for decimal places in your regular expression. Try the following:

\d+(\.\d+)?

This will match the numbers rather than everything other than the numbers, but it should be simple to iterate through the matches to build your array.

Something to keep in mind is whether you should also be looking for negative signs, commas, etc.

Ryan Brunner
+2  A: 

Small improvement to @Michael's solution:

// NOTES: about the LINQ:
// .Where() == filters the IEnumerable (which the array is)
//     (c=>...) is the lambda for dealing with each element of the array
//     where c is an array element.
// .Trim()  == trims all blank spaces at the start and end of the string
var doubleArray = Regex.Split(sentence, @"[^0-9\.]+")
    .Where(c => c != "." && c.Trim() != "");

Returns:

10.4
20.5
40
1

The original solution was returning

[empty line here]
10.4
20.5
40
1
.
code4life
ratty
@ratty intro to LINQ in C#: http://msdn.microsoft.com/en-us/library/bb397897.aspx
cofiem
@ratty: updated my post with comments about the where/trim clauses.
code4life