Sign in to follow this  
Headkaze

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

Recommended Posts

I have the following code

[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());
}
}[/code]

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 this post


Link to post
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 this post


Link to post
Share on other sites
A slightly more elegant solution is [code]"[0-9]+"[/code]; 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 this post


Link to post
Share on other sites
[quote name='GGulati' timestamp='1318907642' post='4873742']
A slightly more elegant solution is [code]"[0-9]+"[/code]; 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).
[/quote]
Except that wouldn't output the format Headkaze was looking for.

[quote name='Headkaze'][color="#1C2837"][size="2"]I want it to output[/size][/color]
[color="#1C2837"][size="2"]
048 3039 49
49
48 39[/quote][/size][/color]

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

Share this post


Link to post
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. [url="http://www.radsoftware.com.au/regexdesigner/"]RegexDesigner[/url]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this