Mano
Mano

Reputation: 987

Regex to validate string having only lower case, first char must be a letter

I want to use the Regex to validate the string containing

I use the /^[\w\s\-.]*$/ to validate the string. But it allows the first character like (._)

Upvotes: 4

Views: 4915

Answers (4)

Darkmouse
Darkmouse

Reputation: 1939

This will probably work for you.

/^[a-z][a-z\d._]*/

/                  - Start of Regex
^                  - The string will start with a lowercase letter
[a-z\d._]*         - The string will have zero or more lowercase letters, digits, etc.
/                  - End of Regex

Hope this helps.

Upvotes: 0

mkHun
mkHun

Reputation: 5927

Try this

 data = "helloworld_12_."
 data =~/^[a-z][a-z\d._]*$/
 puts $&

Upvotes: 0

Michael Laszlo
Michael Laszlo

Reputation: 12239

When you put a period inside square brackets, it is interpreted as a literal period. That's one reason why your regex doesn't work. What you want is this:

input =~ /^[a-z][a-z0-9_.]*$/

Note that the first character is handled with one character class and the remaining characters by another, which is what the specification calls for. You can't pull it off with a single character class.

Upvotes: 2

xbug
xbug

Reputation: 1472

Why don't you just stick to your requirements ?

  • first char must be a lowercase letter: [a-z]
  • remaining characters must match: [a-z0-9_.]

-> your regex: /^[a-z][a-z0-9_.]*$/

Upvotes: 7

Related Questions