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

Regular expression that allows only a specific special character when it has a specific length

I need a regular expression that matches these cases:

EXAMPLE1
1EXAMPLE
EXAMPLE
***** 

Not Match

EXAMPLE 1
EXAMPLE.
**EXAMPLE**
EXAMPLE**
**EXAMPLE
*****EXAMPLE
EXA MPLE
*******
EXAMPLEĂ‘

I try with this regex ^(\*{0,5}?)([a-zA-Z0-9])*$ (DEMO)
but the regular expression matches cases like these which I don’t need to match:

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

*****EXAMPLE
**EXAMPLE
****

They should only match when the asterisks have a length of 5 or words without special characters or asterisks

>Solution :

If you want to match only cases where the entire string either only contains letters and digits, or else is exactly 5 asterisks, you can use the regex ^(\*{5}|[a-zA-Z0-9]+)$ .

This assumes empty strings are not allowed. If you want to allow empty strings, replace + with *.

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