0

I'm trying to create a regular expression that matches strings with:

  • 19 to 90 characters
  • symbols
  • at least 2 uppercase alphabetical characters
  • lowercase alphabetical characters
  • no spaces

I already know that for the size and space exclusion the regex would be:

^[^ ]{19,90}$

And I know that this one will match any a string with at least 2 uppercase characters:

^(.*?[A-Z]){2,}.*$

What I don't know is how to combine them. There is no context for the strings.

Edit: I forgot to say that it is better ifthe regex excludes strings that finish with a .com or .jpeg or .png or any .something (that "something" being of 2-5 characters).

eera5607
  • 305
  • 2
  • 8

3 Answers3

1

This regex should do what you want.

^(?=(?:\w*\W+)+\w*$)(?=(?:\S*?[A-Z]){2,}\S*?$)(?=(?:\S*?[a-z])+\S*?$)(?!.*?\.\w{2,5}$).{19,90}$

Basically it uses three positive lookaheads and a negative lookahead to guarantee the conditions that you specified:

(?=(?:\w*\W+)+\w*$)

ensures that there is at least one non-word (symbol) character

(?=(?:\S*?[A-Z]){2,}\S*?$) 

ensures that there are at least two uppercase characters, and also excludes a match if there are any spaces in the string

(?=(?:\S*?[a-z])+\S*?$)

ensures that there is at least one lowercase character in the string. The negative lookahead

(?!.*?\.\w{2,5}$)

ensures that strings that end with a . and 2-5 characters are excluded

Finally,

.{19.90}

performs the actual match and ensures that there are between 19 and 90 characters.

Nick
  • 138,499
  • 22
  • 57
  • 95
  • Thanks. That was more complicated that I though. Just that I needed to exclude the strings with `.*?\.\w{2,5}` at the end. I this case it is a requirement. – eera5607 Apr 29 '18 at 00:20
  • Your question says you want to exclude strings that **don't** finish with that pattern... – Nick Apr 29 '18 at 00:25
1

Following your requrements, I suggest to use the following pattern:

^(?=.*[a-z])(?=.*[A-Z].*[A-Z])(?=.*[^\s]).{19,90}$

Demo

Instead of just excluding spaces, I used \ssince you probably don't want allow tabs, newlines, etc. either. However, it is still unclear which symbols you want to allow, e.g. [a-zA-Z!"§$%&\/()=?+]

^(?=.*[a-z])(?=.*[A-Z].*[A-Z])(?=.*[^\s])(?=[a-zA-Z!"§$%&\/()=?+]).{19,90}$

To match your additional requirement not to match file-like extensions at the end of the string, add a negative look-ahead: (?!.*\.\w{2,5}$)

^(?=.*[a-z])(?=.*[A-Z].*[A-Z])(?=.*[^\s])(?=[a-zA-Z!"§$%&\/()=?+]).{19,90}$

Demo2

wp78de
  • 18,207
  • 7
  • 43
  • 71
-1

You can use backreferences as described here: https://www.ocpsoft.org/tutorials/regular-expressions/and-in-regex/

Another reference with examples here: https://www.regular-expressions.info/refcapture.html