admin管理员组文章数量:1291122
I am trying to figure out how to use Regex in looking for a comma. I have a form where a user will submit information separated by a comma and I need to verify there is not a comma at the end, or multiple comma together, etc.
I tried this, ^(\w+)(,\s*\w+)*$
, however it did not work because it failed when I added more than 1 word within a , bracket.
Invalid: hello,,,,,,
Invalid: hello, world, , how, are, you
Invalid: hello, world,
Valid: Hello, World
Valid: Hello, World, how are you, doing, today
Valid: .5 cups, 1.5 cups
I am trying to figure out how to use Regex in looking for a comma. I have a form where a user will submit information separated by a comma and I need to verify there is not a comma at the end, or multiple comma together, etc.
I tried this, ^(\w+)(,\s*\w+)*$
, however it did not work because it failed when I added more than 1 word within a , bracket.
Invalid: hello,,,,,,
Invalid: hello, world, , how, are, you
Invalid: hello, world,
Valid: Hello, World
Valid: Hello, World, how are you, doing, today
Valid: .5 cups, 1.5 cups
Share
Improve this question
edited 2 days ago
Peter Thoeny
7,6161 gold badge13 silver badges22 bronze badges
asked Jan 2 at 19:39
letsCodeletsCode
2,9461 gold badge17 silver badges41 bronze badges
4
|
2 Answers
Reset to default 4You may use this regex to validate your inputs:
^[^,\n]+(?: *, *[^,\s][^,\n]*)*$
RegEx Demo
RegEx Details:
^
: Start[^,\n]+
: Match a text that starts 1 or more non-comma, non-newline characters(?:
: Start non-capture group*, *
: Match a comma optionally surrounded by 0 or more spaces[^,\s][^,\n]*
: Match a text that starts with a non-comma, non-whitespace character followed by 0 or more non-comma, non-newline characters
)*
: End non-capture group. Repeat this group 0 or more times$
: End
Code Demo:
const rx = /^[^,\n]+(?: *, *[^,\s][^,\n]*)*$/;
const input = ['hello,,,,,,',
'hello, world, , how, are, you',
'hello, world,',
' hello , world , how , are, you',
'Hello, World',
'Hello, World, how are you, doing, today',
'.5 cups, 1.5 cups']
input.forEach(el =>
console.log(rx.test(el) ? "Valid:" : "Invalid:", el)
)
You can try something like:
^(?:[^\r\n,]*[^\r\n\s,]\s*,)*[^\r\n,]+$
Details:
(?:[^\r\n,]*[^\r\n\s,]\s*,)*
: This group is for at least one non-whitespace char, followed by a comma, repeated zero or more times.[^\r\n,]+
: This is for one non-whitespace char without any comma
本文标签: javascriptRegexvalid string has comma separating wordsStack Overflow
版权声明:本文标题:javascript - Regex, valid string has comma separating words - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736807586a1953754.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
string.split(',')
then check that there are no empty strings in the result? – Barmar Commented Jan 2 at 19:42, *(?:,|$)
– bobble bubble Commented Jan 2 at 21:22\w
does not match.
– The fourth bird Commented Jan 3 at 10:19