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: I need a regex that only allows one comma in string I need a regex that doesn't allow a
Solution 1:
- Allow only one comma (put a
?
behind the second comma if you want to make the comma optional):
^[^,]*,[^,]*$
- Allow only one comma but none at the beginning:
^[^,]+,[^,]*$
- Allow only one comma but none at the end:
^[^,]*,[^,]+$
[^,]
means "a character that is not a comma".
Solution 2:
This regex should do the job.
^[^,]+,[^,]+$
Explanation:
[^,]+
-> Not comma at least once
,
-> comma (obviously)
[^,]+
-> Not comma at least once (again)
Solution 3:
Simple string operations can handle this:
functiontestForComma(str) {
//Comma isn't first character//Comma only exists once//Comma isn't last characterreturn 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(' ,, '));
Solution 4:
simple expression is like - ^[^,]+,[^,]+$
Solution 5:
^(?!.*,.*,)
- 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 ^(?=.*,)
.
Post a Comment for "Regex To Allow One Comma And Not At The Start Or End Of String In Javascript"