# [.net] Using RegEx to output groups of numbers and spaces

This topic is 2434 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I have the following code

 Regex numbersRegex = new Regex("([0-9 ]*)"); MatchCollection numbersMatch = numbersRegex.Matches("jaslkfjaslfk 048 3039 49 askd dlk 49 dlkdkl 48 39 dldl"); if(numbersMatch.Count > 0) { foreach (Match match in numbersMatch) { Console.WriteLine(match.ToString()); } }

I want it to output

048 3039 49
49
48 39

Which it does but it's also outputting each individual space. How can I get it to only output the above?

##### Share on other sites
The '*' means to match zero or more of the character set, and since that's the only thing in your expression, you end up with a bunch of empty matches and single-space matches. Try something like this:

([0-9][0-9 ]*)

It requires that you find at least one digit before you look for zero or more additional digits and spaces. It will also match the trailing space after each string of digits, however a .Trim() will take care of that.

##### Share on other sites
A slightly more elegant solution is "[0-9]+"; the "+" modifier requires 1 or more of the preceding element - e.g., 1 and 10 are valid but a space isn't. You can then use a.Trim(), if need be. Of course, the "[0-9][0-9\\t]*" also works ("\\t" is Regex escaped (NOT C# ESCAPED) for whitespace, including tabs, spaces and newlines).

##### Share on other sites

A slightly more elegant solution is "[0-9]+"; the "+" modifier requires 1 or more of the preceding element - e.g., 1 and 10 are valid but a space isn't. You can then use a.Trim(), if need be. Of course, the "[0-9][0-9\\t]*" also works ("\\t" is Regex escaped (NOT C# ESCAPED) for whitespace, including tabs, spaces and newlines).

Except that wouldn't output the format Headkaze was looking for.

I want it to output
[color="#1C2837"]
048 3039 49
49
48 39

[color="#1C2837"]Maybe that doesn't really matter, I don't know.

##### Share on other sites
(\d+(\s\d)?)+

This should trim as well, regex, so many ways to do the same thing

I find this a useful tool to have when dealing with regex, there are probably better ones that exist now but it suits my needs at least. RegexDesigner

• 34
• 12
• 10
• 9
• 9
• ### Forum Statistics

• Total Topics
631355
• Total Posts
2999514
×