sol
sol

Reputation:

how to write this regular expression?

an 20 - 24 char long alphanumeric string with no spaces and no symbols that has at least 2 digits

AAAAAAAAAAAAAAAAAAAA - not valid
AAAAAA0AAAAAAAAA0AAA - valid
AAAAAA01AAAAAAAAA0AAA - valid
AAAAAA0AAAAAAAAA0AAA@ - not valid

Upvotes: 1

Views: 321

Answers (6)

CAFxX
CAFxX

Reputation: 30301

in JS (not confident enough with C# syntax):

if (str.length >= 20 && str.length <= 24 && /([a-z]*[0-9]){2}[a-z0-9]*/i.test(str)) {
  // match found
}

Upvotes: 0

Guffa
Guffa

Reputation: 700242

I think that this is the simplest pattern: First make a positive lookahead to check that there are at least two digits, then match 20-24 alphanumeric characters:

^(?=.*\d.*\d)[A-Za-z\d]{20,24}$

Upvotes: 2

kennebec
kennebec

Reputation: 104760

Gumbo has a correct expression for the requirements.

It could be shortened, but his was more clear and probably faster than the short version.

var rX=/^(?=[a-zA-Z\d]{20,24}$)([a-zA-Z]*\d){2,}/

Upvotes: 1

Tsundoku
Tsundoku

Reputation: 9408

Basically the same idea as Gumbo just a little shorter:

^(?=[\w\d]{20,24}$)[\w]*\d[\w]*\d[\w\d]*$

Upvotes: -1

MarkusQ
MarkusQ

Reputation: 21950

I'm going to be abstract because this sounds like homework (if it is, please tag it as such).

  • You can restrict the number of times a pattern matches with {min,max}
  • You can restrict which characters match with [charlist]
  • You can impose additional restrictions with what's called zero-width positive lookahead (there's also a negative form). The syntax varies, so check the docs for your environment.

Update your question (& tags) if you need more help.

Upvotes: 1

Gumbo
Gumbo

Reputation: 655209

I think this is only possible with look-ahead assertion:

^(?=[a-zA-Z\d]{20,24}$)[a-zA-Z]*\d[a-zA-Z]*\d[a-zA-Z\d]*$

The look-ahead assertion ((?=[a-zA-Z\d]{20,24}$)) checks if the string has the expected form (20–24 alphanumeric characters). And the second part ([a-zA-Z]*\d[a-zA-Z]*\d[a-zA-Z\d]*) checks if it contains at least two digits.

Upvotes: 5

Related Questions