tags:

views:

151

answers:

5

Ok so I finally figured out that I need the following:

So the regular expression has to perform:

  1. alphanumeric
  2. at least 1 letter
  3. must have between 4 and 8 characters (either a letter/digit).

i.e. an alphanumeric string, that must have at least 1 letter, and be between 4-8 in length. (so it can't be just all numbers or just all letters).

can all of this be done in a single regex?

+1  A: 

number 2 and 3 seem to contradict. The following will match alphanumeric between 4 and 8:

/[0-9a-zA-Z]{4,8}/
Marius
2 doesn't contradict 3, but is redundant.
Nick Dixon
@Nick Dixon- depends what you interpret them as meaning!
RichardOD
I clarified my post above.
mrblah
A: 
[a-zA-Z0-9]{4,8}

The first part specifies alphanumeric, and the 2nd part specifies from 4 to 8 characters.

CodeJoust
A: 

Try: [a-zA-Z0-9]{4,8}

Joe
+9  A: 

I'm assuming you mean alphaunumeric, at least one letter, and 4 to 8 characters long.

Try this:

(?=.*[a-zA-Z])[a-zA-Z0-9]{4,8}
  • (?= - we're using a lookahead, so we can check for something without affecting the rest of the match

  • .*[a-zA-Z] - match for anything followed by a letter, i.e. check we have at least one letter

  • [a-zA-Z0-9]{4,8} - This will match a letter or a number 4 to 8 times.

However, you say the intention is for "it can't be just all numbers or just all letters", but requirements 1, 2 and 3 don't accomplish this since it's can be all letters and meet all three requirements. It's possible you want this, with an extra lookahead to confirm there's at least one digit:

(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]{4,8}

The use of a-zA-Z isn't very international friendly, so you may be better off using an escape code for "letter" if available in your flavour of Regular Expressions.

Also, I hope this isn't matching for acceptable passwords, as 4 characters probably isn't long enough.

Dave Webb
That's how I read it.
Matt Ellen
**.\*** => **.+**
serhio
It shouldn't be .+ since then it wouldn't match 1aaa for example.
Dave Webb
@Dave: you are wrong. .+ means at least **one** but .* cound match by eg. "1111". ?Regex.IsMatch("1aaa", "(?=.+[a-zA-Z])[a-zA-Z0-9]{4,8}")**true**; ?Regex.IsMatch("1111", "(?=.*[a-zA-Z])[a-zA-Z0-9]{4,8}")**false**
serhio
The lookahead is there to check if a letter is in the pattern, that is all, which is why it uses * as there letter can appear anywhere in the patter, even first. What I should have said is that if I use .+ the it won't match a111 (not 1aaa).
Dave Webb
+1  A: 
?Regex.IsMatch("sdf", "(?=.+[a-zA-Z])[a-zA-Z0-9]{4,8}")
false
?Regex.IsMatch("sdfd", "(?=.+[a-zA-Z])[a-zA-Z0-9]{4,8}")
true
?Regex.IsMatch("1234", "(?=.+[a-zA-Z])[a-zA-Z0-9]{4,8}")
false

Warning on *. and .+:

// At least one letter does not match with .*
?Regex.IsMatch("1111", "(?=.*[a-zA-Z])[a-zA-Z0-9]{4,8}")
false

?Regex.IsMatch("1aaa", "(?=.+[a-zA-Z])[a-zA-Z0-9]{4,8}")
true
serhio