Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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}/

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading