简体   繁体   中英

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

/^([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
  • (?:(?:\\*|[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\\/]+|\\*))* - zero or more sequences of:
      • , - a comma
      • (?:[A-Za-z\\d\\/]+|\\*) - 1 or more alphanumeric or / symbols or a *
  • $ - 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.
    • Since we have [^*]*, , 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 \\ ;
  • Again, we have `([^ ] ,)?
  • $ 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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