OrElse
OrElse

Reputation: 9959

Regex for alphanumeric (unicode) with specific length

Valid ones should contain at least one number or letter (from 6 to 15 chars long) in any order. e.x.

11111a

111a11

a11111

I found similar posts within SO but they seem to be out of order...

Upvotes: 2

Views: 1870

Answers (4)

amitkaz
amitkaz

Reputation: 2712

That should do it: \w{6,15} if you want to match the whole string: ^\w{6,15}$

Upvotes: -1

Heiko Hatzfeld
Heiko Hatzfeld

Reputation: 3197

You would need a look ahead query for that one.

You can create a regexp token that will try to find a match, but will not "consume" the input string. You can follow that one with a simple 2nd query that will validate the length of your string.

You can combine those to create the query you desire.

The syntax for the .Net Version of the RegEx engine would be something like this:

This RegEx is only written in this chatbox, and not tested... so have mercy :)

I am not sure whats a "Character or letter, but I will assume you mean "a-Z"

(?=.*[a-zA-Z]).{6,15}

Upvotes: 0

Steve Wortham
Steve Wortham

Reputation: 22220

Looks like this works:

^(?=.*[a-zA-Z].*)\w{6,15}(?<=.*\d.*)$

And here it is with test cases:

http://regexhero.net/tester/?id=83761a1e-f6ae-4660-a91f-9cdc4d69c7b3

Basically my idea was to use a positive lookahead first to ensure at least one letter is included. Then I use \w{5,16} as a simple means of ensuring that I match the correct number of characters (and that they are alphanumeric). And then at the end I use a positive lookbehind to ensure that the string includes at least one number as well.

Upvotes: 0

Philippe Leybaert
Philippe Leybaert

Reputation: 171764

This will match 6 to 15 characters (letters or digits), except all digits or all letters:

^(\p{L}|\p{N}){6,15}(?<=\p{L}.*)(?<=\p{N}.*)$

aaaaa1aaaa matches

1111111a11 matches

aaaaaaaaaa doesn't match

1111111111 doesn't match

Upvotes: 3

Related Questions