H. Lafor
H. Lafor

Reputation: 21

C# Regex Validation

Can someone please validate this for me (newbie of regex match cons).
Rather than asking the question, I am writing this:

Regex rgx = new Regex (@"^{3}[a-zA-Z0-9](\d{5})|{3}[a-zA-Z0-9](\d{9})$"

Can someone telll me if it's OK...

The accounts I am trying to match are either of:

1. BAA89345  (8 chars)
2. 12345678  (8 chars)
3. 123456789112 (12 chars)

Thanks in advance.

Upvotes: 2

Views: 286

Answers (5)

smartcaveman
smartcaveman

Reputation: 42276

I'm not 100% on your objective, but there are a few problems I can see right off the bat.

  1. When you list the acceptable characters to match, like with a-zA-Z0-9, you need to put it inside brackets, like [a-zA-Z0-9] Using a ^ at the beginning will negate the contained characters, e.g. `[^a-zA-Z0-9]

  2. Word characters can be matched like \w, which is equivalent to [a-zA-Z0-9_].

  3. Quantifiers need to appear at the end of the match expression. So, instead of {3}[a-zA-Z0-9], you would need to write [a-zA-Z0-9]{3} (assuming you want to match three instances of a character that matches [a-zA-Z0-9]

Upvotes: 0

Mitch
Mitch

Reputation: 22301

Although that may be a perfectly valid match, I would suggest rewriting it as:

^([a-zA-Z]{3}\d{5}|\d{8}|\d{12})$

which requires the string to match one of:

  • [a-zA-Z]{3}\d{5} three alpha and five numbers
  • \d{8} 8 digits or
  • \d{12} twelve digits.

Makes it easier to read, too...

Upvotes: 1

skunkfrukt
skunkfrukt

Reputation: 1570

You need to place your quantifiers after the characters they are supposed to quantify. Also, character classes need to be wrapped in square brackets. This should work:

@"^(?:[a-zA-Z0-9]{3}|\d{3}\d{4})\d{5}$"

There are several good, automated regex testers out there. You may want to check out regexpal.

Upvotes: 1

DRobertE
DRobertE

Reputation: 3508

Is the value with 3 characters then followed by digits always starting with three... can it start with less than or more than three. What are these mins and max chars prior to the digits if they can be.

Upvotes: 1

System Down
System Down

Reputation: 6270

You can use a Regex tester. Plenty of free ones online. My Regex Tester is my current favorite.

Upvotes: 1

Related Questions