Simple regex problem

nbrege

Active member
Joined
Jan 12, 2006
Messages
34
I have never used regular expressions before so please excuse my stupidity. I just need to check for strings that matches a particular pattern, in this case, a "J" followed by six digits. ie. "Jxxxxxx"

Here is the psuedo code:

If testString = "Jxxxxxx" Then

do some stuff

End If



Can someone show me how to code this in VB2005express? I searched through the forums but couldnt find any examples. Thanks...
 
I think it would be something like (shooting from the hip):
Code:
If Regex.IsMatch(testString, "J[0-9]{6}") Then
   Do stuff
End If

J[0-9]{6} says that the string must start with J, then have 6 digits after that but I dont care what the digits are. I think you might be able to swap the 0-9 for a /d as well, but I dont remember off the top of my head. Remember youll need to import the System.Text.RegularExpression namespace at the top of the file.
 
Thanks, it worked! Heres another one for you ... suppose I want to match all strings that either start with "J" followed by 6 digits (ie. "Jxxxxx") or just start with 6 digits (ie. "xxxxxx")? The leading "J" may or may not be present. Can I do that with one regex? Thanks...
 
Last edited by a moderator:
Of course! :D

Using the 0 or 1 operator, ?, you get "J?[0-9]{6}". So, that says you want a string with either 0 or 1 Js followed by exactly 6 digits.

I highly reccomend you get a regex tool to help you out with this stuff. Little tools like some of the ones listed here are extremely helpful. There are also a couple of links to information in general about Regex.
 
Thanks yet again. One last question for you ... is it possible to specify two completely different patterns in the same regex? Is there some sort of OR operator I can use?

I will check out some of the tools you suggested so I dont have to keep bugging you about this...
 
I merely suggest a helper tool so you dont have to wait for replies and can do more advanced stuff easily on your own. :)

The or operator, |, is exactly what you need.

So something like "(choo)|J?[0-9]{6}" would give you a string that is either "choo" or 6 digits possibly preceded by a J.

Valid strings for this regex => "J123456", "123456", "choo", ...
Invalid strings for this regex => "j123456", "J123", "cho", "12Cho", "Choo", "duh", "J12345", ...
 
Back
Top