C# regex help

Status
Not open for further replies.
csharpregex-1.jpg


EDIT: lol just realized line numbers was off for some reason. Image updated.
 
Thanks, that works.

But, I can still add letters after the numbers in the last octet.

Code:
Regex pattern = new Regex(
                @"(?<First>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Second>2[0-4]\d|25"
                + @"[0-5]|[01]?\d\d?)\.(?<Third>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?"
                + @"<Fourth>2[0-4]\d|25[0-5]|[01]?\d\d?)",
                RegexOptions.IgnoreCase
                | RegexOptions.CultureInvariant
                | RegexOptions.IgnorePatternWhitespace
                | RegexOptions.Compiled
            );

How can I fix that?
 
Your code didn't work. Firstly I was required to use three numbers in each octet. I want it to accept only 1-3 numbers. I fixed that by changing {2} to {1,3}. Then I could only put two or three numbers in, one number didn't match because you put [0-9] twice. I made it so it was was like [0-9]{1,3}, but that gets me back to the same code I already messed with earlier and I don't get the results I want.


Ok,
Regex pattern = new Regex("[0-9][0-9]{0,2}.[0-9][0-9]{0,2}.[0-9][0-9]{0,2}.[0-9][0-9]{9,2}");

That should work. The fact that there are two [0-9]'s won't matter because the second is set to repeat from 0 to 2 times. If it repeats 0 times then only the first [0-9] will come into play.
 
Thanks, that works.

But, I can still add letters after the numbers in the last octet.

Code:
Regex pattern = new Regex(
                @"(?<First>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Second>2[0-4]\d|25"
                + @"[0-5]|[01]?\d\d?)\.(?<Third>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?"
                + @"<Fourth>2[0-4]\d|25[0-5]|[01]?\d\d?)",
                RegexOptions.IgnoreCase
                | RegexOptions.CultureInvariant
                | RegexOptions.IgnorePatternWhitespace
                | RegexOptions.Compiled
            );

How can I fix that?

Add a word boundry \b to the end.
 
Add a word boundry \b to the end.

Thanks, that worked for letters, but the following characters are still allowed: ? / . , + = - ! ' " ; : ( ) [ ] { } \ | ` ~

All of those characters, if used after a number, matches. I know that in regex, it makes more logical sense in these situations to only match what you WANT it to look like, and not match everything else. So, how do I do that in this case?

My code now:
Code:
Regex pattern = new Regex(
                @"(?<First>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Second>2[0-4]\d|25"
                + @"[0-5]|[01]?\d\d?)\.(?<Third>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?"
                + @"<Fourth>2[0-4]\d|25[0-5]|[01]?\d\d?)\b",
                RegexOptions.IgnoreCase
                | RegexOptions.CultureInvariant
                | RegexOptions.IgnorePatternWhitespace
                | RegexOptions.Compiled
            );
 
Status
Not open for further replies.
Back
Top Bottom