Home > database >  Regex for only letters and numbers but no numbers at the beginning or end
Regex for only letters and numbers but no numbers at the beginning or end

Time:12-11

I want to make a regex that matches only letters and numbers, but no numbers at the beginning or the end:

  • ahmed0saber is valid
  • 0ahmedsaber is not valid
  • ahmedsaber0 is not valid
  • ahmed_saber is not valid

I tried this

[a-z0-9_]

but it doesn't work as expected!

CodePudding user response:

This should work ^[a-z][a-z\d]*[a-z]$

const regex = /^[a-z][a-z\d]*[a-z]$/
const tests = ['ahmed0saber', '0ahmedsaber', 'ahmedsaber0', 'ahmed_saber']
tests.forEach(test)

function test(name) {
  console.log(name, name.match(regex) ? 'yes' : 'no')
}

CodePudding user response:

If you also want to allow a single character:

 ^[a-z](?![a-z\d]*\d$)[a-z\d]*$

Explanation

  • ^ Start of string
  • [a-z] Match a single char a-z
  • (?![a-z\d]*\d$) Negative lookahead, assert the the string does not end on a digit
  • [a-z\d]* Match optional chars a-z or digits
  • $ End of string

See a regex demo.

Or if a lookbehind assertion is supported:

^[a-z][a-z\d]*$(?<!\d)

Explanation

  • ^ Start of string
  • [a-z] Match a single char a-z
  • [a-z\d]* Match optional chars a-z or digits
  • $ End of string
  • (?<!\d) Negative lookabehind, assert not a digit at the end

See another regex demo.

  • Related