简体   繁体   中英

regex to allow one comma and not at the start or end of string in JavaScript

I am not very good at regex and I need 3 different regex's that follow the following rules:

  1. I need a regex that only allows one comma in string
  2. I need a regex that doesn't allow a comma at the start of a string but still allow only one comma.
  3. I need a regex that doesn't allow a comma at the end of a string but still allow only one comma.

For the first rule: 21, day would be okay but 21, day, 32 would not be okay.

For the second rule: ,21 would not be okay.

For the third rule: 21, would not be okay.

So far I have created a regex below which accommodates for the rules above but I was wondering if it could be split up into three different regex's that can accommodate for the three above rules.

^[a-z0-9A-Z&.\/'_ ]+(,[a-zA-Z0-9&.\/'_ ]+)?$

Any help would be much appreciated. Thanks

  1. Allow only one comma (put a ? behind the second comma if you want to make the comma optional):
        ^[^,]*,[^,]*$
  1. Allow only one comma but none at the beginning:
        ^[^,]+,[^,]*$
  1. Allow only one comma but none at the end:
        ^[^,]*,[^,]+$

[^,] means "a character that is not a comma".

This regex should do the job.

^[^,]+,[^,]+$

Explanation:

[^,]+ -> Not comma at least once

, -> comma (obviously)

[^,]+ -> Not comma at least once (again)

  1. ^(?!.*,.*,) - this is the base regex rejecting recurrent commas.
  2. ^(?!,)(?!.*,.*,) - the same base with added "no comma at the start" condition
  3. ^(?!.*,.*,).*(?:[^,]|^)$ - the same base with "no comma at the end". The latter is implemented as alternation group match since lookbehinds are not available in JavaScript.

Note: all these patterns allow zero or one comma in the input. If you need strictly one comma, prepend each of them with ^(?=.*,) .

Simple string operations can handle this:

 function testForComma(str) { //Comma isn't first character //Comma only exists once //Comma isn't last character return str.indexOf(',') >= 1 && str.lastIndexOf(',') == str.indexOf(',') && str.lastIndexOf(',') != str.length - 1; } console.log(testForComma(',')); console.log(testForComma(', ')); console.log(testForComma(' ,')); console.log(testForComma(' , ')); console.log(testForComma(' ,, '));

简单的表达就像 - ^[^,]+,[^,]+$

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