'RegExp pattern for alphanumeric with underscore or hypen

I searched & tried below RegExp, but, not working for my requirement. Please, provide PHP RegExp, which accepts at least one alphanumeric and optional underscore or hyphen, but, Underscore or Hyphen should not repeat twice in a row.

/^([a-z0-9]+-)*[a-z0-9]+$/i

Example formats

  1. _test147
  2. test
  3. _a
  4. test_test
  5. test-test_, etc


Solution 1:[1]

You may use this regex in ignore case mode:

^[-_]?[a-z\d]+(?:[_-][a-z\d]+)*[-_]?$

RegEx Demo

RegEx Details:

  • ^: Start
  • [-_]?: Match an optional _ or -
  • [a-z\d]+: Match 1+ of alphanumeric character
  • (?:: Start a non-capture group
    • [_-]: Match a _ or -
    • [a-z\d]+: Match 1+ of alphanumeric character
  • )*: End non-capture group. Repeat this group 0 or more times
  • [-_]?: Match an optional _ or -
  • $: End

Or else if you want even better performance then use this possessive quantifier regex:

^[-_]?[a-z\d]++(?:[_-][a-z\d]+)*[-_]?+$

Solution 2:[2]

/^([-_]?[a-z0-9]+)+[-_]?$/i

This has a repeating sequence with an optional hyphen or underscore followed by alphanumerics, and then allows another optional hyphen or underscore at the end.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Barmar