[英]Allow star only once and not allow it not to be mixed with any other
I have below regex. 我有以下正则表达式。 i want to validate like abcd,*,acd123
etc. I dont want * to be mixed with any like abc* and it should be allowed only once ex following should be rejected ** or *,*
我想验证像abcd,*,acd123
等。我不希望*与任何类似的abc *混合,并且应该只允许其中一个以下应该被拒绝** or *,*
/^([A-Za-z\d\/\*]+(,[A-Za-z\d\/\*]+)*)?$/.test(v)
valid: 有效:
ADSAD,*,adsad
*,adsds,asd123
Invalid: 无效:
**,asads
sasd,*,asa,*
Put the *
out of the character classes and only allow it as an alternative to the alphanumeric or /
symbols: 将*
放在字符类之外,只允许它作为字母数字或/
符号的替代:
/^(?!.*\*.*\*)(?:(?:\*|[A-Za-z\d\/]+)(?:,(?:[A-Za-z\d\/]+|\*))*)?$/
See the regex demo 请参阅正则表达式演示
Details : 细节 :
^
- start of string ^
- 字符串的开头 (?!.*\\*.*\\*)
- a negative lookahead that fails the match once there are 2 *
symbols in the string (?!.*\\*.*\\*)
- 一旦字符串中有2 *
符号就会使匹配失败的负向前瞻 (?:(?:\\*|[A-Za-z\\d\\/]+)(?:,(?:[A-Za-z\\d\\/]+|\\*))*)?
- an optional group (the whole string can be empty) matching: - 一个可选组(整个字符串可以为空)匹配:
(?:\\*|[A-Za-z\\d\\/]+)
- a *
( \\*
) or ( |
) 1 or more alphanumeric or /
symbols ( [A-Za-z\\d\\/]+
), then followed with (?:\\*|[A-Za-z\\d\\/]+)
- a *
( \\*
)或( |
)1个或多个字母数字或/
符号( [A-Za-z\\d\\/]+
),然后跟着 (?:,(?:[A-Za-z\\d\\/]+|\\*))*
- zero or more sequences of: (?:,(?:[A-Za-z\\d\\/]+|\\*))*
- 零个或多个序列:
,
- a comma ,
- 一个逗号 (?:[A-Za-z\\d\\/]+|\\*)
- 1 or more alphanumeric or /
symbols or a *
(?:[A-Za-z\\d\\/]+|\\*)
- 1个或多个字母数字或/
符号或*
$
- end of string. $
- 结束字符串。 I am not sure it will solve your whole problem, but the posted question can be solved this way: 我不确定它会解决你的整个问题,但发布的问题可以这样解决:
^([^*]*,)?\*(,[^*]*)?$
where 哪里
^
is the start of the string; ^
是字符串的开头; [^*]
is any character that is not an asterisk. [^*]
是任何不是星号的字符。
[^*]*,
, it means any number of characters that are not asterisks, followed by a comma; 由于我们有[^*]*,
它表示任何不是星号的字符,后跟逗号; ([^*]*,)?
means we have zero or at most one of these in the string. 意味着我们在字符串中有零个或最多一个。 \\*
is the asterisk char. \\*
是星号字母。 Since it is a special one, we need to escape it with \\
; 因为它是一个特殊的,我们需要用\\
来逃避它; $
means the end of the string. $
表示字符串的结尾。 Here is the result: 结果如下:
> /^([^*]*,)?\*(,[^*]*)?$/.test('abc,*,def')
true
> /^([^*]*,)?\*(,[^*]*)?$/.test('abc,def')
false
> /^([^*]*,)?\*(,[^*]*)?$/.test('abc,*,def,*,a')
false
> /^([^*]*,)?\*(,[^*]*)?$/.test('abc,*')
true
> /^([^*]*,)?\*(,[^*]*)?$/.test('*,abc')
true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.