How to write regex to verify a comma delimited list of values

后端 未结 4 1408
日久生厌
日久生厌 2021-01-03 02:32

I am using SobiPro, a directory system for joomla and I have a field that will have values that contain alphanumerics and hyphens only, so a sample of what might be in this

相关标签:
4条回答
  • 2021-01-03 03:08

    Try this:

    ^[-\w\s]+(?:,[-\w\s]*)*$
    

    Using ^ and $ ensures that we validate the entire value, and don't just find a match somewhere within.

    The first character class, [-\w\s]+ allows one or more alphanumeric, whitespace, or dash characters. The dash should go first in the class brackets.

    The second group allows zero or more repetitions with separating commas. It is wrapped in non-capturing parentheses, a small performance optimization: (?: … )*

    Notes:

    • This expression allows empty entries, such as A,B,,D. If you don't want to allow this, change the second-to-last * to a +.
    • The \w shorthand allows underscores. To prevent this, replace them with A-Za-z0-9.
    0 讨论(0)
  • 2021-01-03 03:12

    You can use a character class for this:

    [\w\s-]+(,[\w\s-]*)*
    

    I've made the character class inside the group optional in order to allow empty fields.

    If your validator doesn't force the regex to always match the entire input field, you may need to anchor it by surrounding it with ^ at the start and $ at the end.

    0 讨论(0)
  • 2021-01-03 03:16

    Use character classes.

    ^([0-9A-Za-z -]+)(,[0-9A-Za-z -]+)*$
    

    Note that \w includes underscores, which is why I'm expanding it to alphanumeric ranges.

    Thanks to @Jay for pointing out missing anchors.

    0 讨论(0)
  • 2021-01-03 03:20

    Try this:

    [-\w\s]+(,[-\w\s]+)*
    

    [-\w\s] means a word character, space or hyphen.

    A word character usually includes _, so you may want to replace that with A-Za-z0-9 if you want to prevent this.

    [-A-Za-z0-9\s]+(,[-A-Za-z0-9\s]+)*
    
    0 讨论(0)
提交回复
热议问题