What is a regex for Twitter-like names?

I have been coding for a while but never had the need for regular expressions until recently. I need to do a regular expression that accepts usernames as Twitter does. Basically, I want to allow one underscore at a time. There can be more than one underscore in a name but these should not be consecutive characters. Alphanumeric characters are also allowed. But numbers cannot start a name.

Names such as

  • _myname67
  • myname67
  • my_name
  • _my_67_name_

are valid but

  • 94myname
  • __myname
  • my__name
  • my name

are not valid.

I have played with Rubular and come up with a couple regexes:

  • /^[^0-9\s+](_?[a-z0-9]+_?)+$/i
  • /^([a-z_?])+$/i

The problem I keep running into is that these match more than one underscores.

8
задан the Tin Man 16 May 2011 в 23:50
поделиться