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

Time:07-29

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:

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

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

CodePudding user response:

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 *.

CodePudding user response:

It is not totally clear to me what to match in your case, however, something like

(^\*{5}$)|(^[a-zA-Z0-9] $)

Should do the trick.

  • Related