Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex, valid string has comma separating words

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
like image 862
letsCode Avatar asked Sep 02 '25 14:09

letsCode


2 Answers

You 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)
)
like image 127
anubhava Avatar answered Sep 05 '25 06:09

anubhava


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
like image 22
awz Avatar answered Sep 05 '25 07:09

awz