skip to Main Content

I am trying to figure out how to use Regex in looking for a comma. I have a form where A usser will submit information seperated by a comma and I need to verify there is not a comma at the end, or mult 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

2

Answers


  1. 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)
    )
    Login or Signup to reply.
  2. You can try something like:

    ^(?:[^rn,]*[^rns,]s*,)*[^rn,]+$
    

    Details:

    • (?:[^rn,]*[^rns,]s*,)*: This group is for at least one non-whitespace char, followed by a comma, repeated zero or more times.
    • [^rn,]+: This is for one non-whitespace char without any comma
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search