Sabri Aziri
Sabri Aziri

Reputation: 4184

Regular Expression for name field

I am using this code but it doesn't work correctly for - (mains) symbol

^\b\w{1,}(_\.-)?\w\b$ or ^\b\w{1,}(_\.\-)?\w\b$

The code above doesn't work if string is like this: name-name

What I want to do with this code is: Name most begin with Alphanumeric and aslo end, it can have this symbols (.-_) but only in the middle

name => true
Name_ => false
Name_sa => true
name._ => false  
name.-as => false

Upvotes: 0

Views: 185

Answers (3)

Win32
Win32

Reputation: 1149

There are two main problems with that regex:

  • You are forgetting to allow multiple repetitions of the final \w
  • You are only allowing one of those special symbols inside name

Also, instead of {1,} you can also use +, which makes it more readable. So this regex should achieve what you want:

/^\b\w[\w_.-]*\w\b$/

Upvotes: 1

Gumbo
Gumbo

Reputation: 655269

I think this should do it:

^[^\W_]+([_.-][^\W_]+)?$

Here the [^\W_] matches only any character except non-word characters and the _, so basically any word character except _. This is necessary as \w does contain _.

Upvotes: 4

Michael Mior
Michael Mior

Reputation: 28762

name-name should work. If you want something like name.-as to work, you need to change the ? to * to allow for multiple characters in the middle.

Upvotes: 0

Related Questions