Home > Mobile >  Regex Assistance - alphanumeric string separated by comma and/or space
Regex Assistance - alphanumeric string separated by comma and/or space

Time:10-07

Need to have alphanumeric string separated by comma (needed) and/or space(not required to have it but user can enter and that is acceptable)

So, "ab1c,def2, efg657hi" is fine. Prefer no leading trailing , or space, but not a show stopper

I have the following but don't think it's complete.

[0-9a-zA-Z]? (,\s[0-9a-zA-Z] )*

CodePudding user response:

The pattern [0-9a-zA-Z]? (,\s[0-9a-zA-Z] )* that you tried uses a possessive quantifier ? which means it either matches 1 character or no character, but when it matches it does not allow for backtracking.

As the second part is optional (,\s[0-9a-zA-Z] )* the whole pattern can also match an empty string or for example a leading comma , abd

To make the pattern match the whole string, you can add anchors to prevent partial matches, and repeat the leading character class 1 or more times.

If you also want to allow for optional whitespace chars before the comma you can add another \s* before it:

^[0-9a-zA-Z] (?:\s*,\s*[0-9a-zA-Z] )*$

See a regex demo.

Note that \s can also match a newline.

CodePudding user response:

Need to have alphanumeric string separated by comma (needed) and/or space (not required to have it but user can enter and that is acceptable)

I'd advise:

^(?!.*_)\w (?:,? ?\w )*$

See an online demo

  • ^ - Start string anchor.
  • (?!.*_) - Negative lookahead to prevent 0 characters and underscore.
  • \w - 1 Word-characters, short for [0-9a-zA-Z_].
  • (?: - Open non-capture group:
    • ,? ? - Optional comma and optional space to allow for all variations mentioned, e.g. comma and/or space (not required).
    • \w - 1 Word-characters, short for [0-9a-zA-Z_].
    • )* - Close non-capture group and match 0 times.
  • $ - End string anchor.

Note that you could remove the negative lookahead and use the extended character class instead of \w.

  • Related