Home > Net >  Further narrow down regex character set so that one uppercase is mandatory
Further narrow down regex character set so that one uppercase is mandatory

Time:10-27

I have a long string like aaaaa123 ** bbbbb444 ** ccccc66 ** ddDddD77 ** eeeee667 and want to grab a substring using a Regex.

What I've got so far:

/[A-Z,a-z,0-9,_-]{7,14}/

This should return any group of 7 to 14 characters consisting of uppercase, lowercase, digits - and _

So far so good.

However, I now want it to be more strict so that at least one uppercase character is mandatory. I.e. in my example only ddDddD77 should match. How do I do that?

CodePudding user response:

If a lookahead and \w is supported and the word does not start or end with - you can assert for the length and match at least an uppercase:

\b(?=[\w-]{7,14}\b)[a-z0-9_-]*[A-Z][\w-]*

Regex demo

Another option:

(?<!\S)(?=[\w-]{7,14}(?!\S))[a-z0-9_-]*[A-Z][\w-]*

Regex demo

If the lookbehind is not supported, you could also opt for a capture group:

(?:\s|^)(?=[\w-]{7,14}(?:\s|$))([a-z0-9_-]*[A-Z][\w-]*)

Regex demo

  • Related