I am not very good at regex and I need 3 different regex's that follow the following rules:
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
?
behind the second comma if you want to make the comma optional): ^[^,]*,[^,]*$
^[^,]+,[^,]*$
^[^,]*,[^,]+$
[^,]
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)
^(?!.*,.*,)
- this is the base regex rejecting recurrent commas. ^(?!,)(?!.*,.*,)
- the same base with added "no comma at the start" condition ^(?!.*,.*,).*(?:[^,]|^)$
- 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.