简体   繁体   English

正则表达式,当它具有特定长度时只允许特定的特殊字符

[英]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:我尝试使用这个正则表达式^(\*{0,5}?)([a-zA-Z0-9])*$ (DEMO)但正则表达式匹配这些我不需要匹配的情况:

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

They should only match when the asterisks have a length of 5 or words without special characters or asterisks只有当星号的长度为 5 或没有特殊字符或星号的单词时,它们才应该匹配

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]+)$ .如果您只想匹配整个字符串仅包含字母和数字,或者正好是 5 个星号的情况,您可以使用正则表达式^(\*{5}|[a-zA-Z0-9]+)$ .

This assumes empty strings are not allowed.这假定不允许使用空字符串。 If you want to allow empty strings, replace + with * .如果要允许空字符串,请将+替换为*

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.应该做的伎俩。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM