Mazen Elhamy
Mazen Elhamy

Reputation: 45

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

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

I tried this

[a-z0-9_]

but it doesn't work as expected!

Upvotes: 1

Views: 803

Answers (2)

The fourth bird
The fourth bird

Reputation: 163632

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.

Upvotes: 3

Konrad
Konrad

Reputation: 24691

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')
}

Upvotes: 2

Related Questions