Home > Software design >  RegExp pattern for alphanumeric with underscore or hypen
RegExp pattern for alphanumeric with underscore or hypen

Time:02-04

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

CodePudding user response:

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

CodePudding user response:

/^([-_]?[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.

  •  Tags:  
  • Related