Link to home
Start Free TrialLog in
Avatar of hankknight
hankknightFlag for Canada

asked on

ASP.NET/C#/REGEX: Test if string fits my format

I want to test if a string fits my special format.

[Empty or Number between 1 and 5000]x[Empty or Number between 1 and 5000]

These should all return true:
5000x5000
x250
x
250x
200x123

These should all return false:
abcx123
200
0x100
100x5001
SOLUTION
Avatar of guru_sami
guru_sami
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Aah...didn't test enough...thanks for pointing out.
No problem...  I have to do range regex often enough and yours was a lot shorter than I normally do.  I had a brief moment when I was thinking, have I been doing this the hard way all long?
Still testing but how does it look now?
^((\s*[1-9]{0,3})|(\s*|5000)|(\s*|[1-4]\d{0,3}))x((\s*[1-9]{0,3})|(\s*|5000)|(\s*|[1-4]\d{0,3}))$

Open in new window


--Valid
5000x5000
x250
x
250x
200x123
4999x
999x

--Invalid
abcx123
200
100x5001
6000x
900
0x100
600x
Avatar of kaufmed
Slightly shorter version (give points to gt2847c, though, as upon further inspection it is the same pattern. His generous use of brackets threw me off at first!):

^(5000|[1-4]\d{3}|[1-9]\d\d|[1-9]\d|[1-9])?x(5000|[1-4]\d{3}|[1-9]\d\d|[1-9]\d|[1-9])?$

Open in new window

guru_sami, your regex still matches 0x, but closer.  kaufmed, thx for shortening it.  I'll stick that in my bag of tricks.  Always useful to learn something better while helping out...

I do a lot of regex with SSIS input validation, so shorter is better =)
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial