Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex only allow letters and some characters

Tags:

regex

I am attempting to create a regex that only allows letters upper or lowercase, and the characters of space, '-', ',' '.', '(', and ')'. This is what I have so far but for some reason it is still letting me enter numbers

^[a-zA-Z -,.()]*$

any help would be great! Thanks.

like image 918
newToRegex Avatar asked Dec 22 '10 15:12

newToRegex


People also ask

How do I allow certain characters in regex?

There is a method for matching specific characters using regular expressions, by defining them inside square brackets. For example, the pattern [abc] will only match a single a, b, or c letter and nothing else.

How do I allow only letters and numbers in regex?

You can use regular expressions to achieve this task. In order to verify that the string only contains letters, numbers, underscores and dashes, we can use the following regex: "^[A-Za-z0-9_-]*$".

How do I restrict the alphabet in regex?

If you wish to use a regex constraint on a number in a text type question, make sure you always have the value numbers under the appearance column. This restricts the display of alphabets, making only numbers visible for inputs.

What does \b mean in regex?

The word boundary \b matches positions where one side is a word character (usually a letter, digit or underscore—but see below for variations across engines) and the other side is not a word character (for instance, it may be the beginning of the string or a space character).


1 Answers

- is special in character class. It is used to define a range as you've done with a-z.

To match a literal - you need to either escape it or place it such that it'll not function as range operator:

^[a-zA-Z \-,.()]*$
         ^^ escaping \ 

or

^[-a-zA-Z ,.()]*$
  ^ placing it at the beginning.

or

^[a-zA-Z -,.()-]*$
              ^ placing it at the end.

and interestingly

^[a-z-A-Z -,.()]*$
     ^ placing in the middle of two ranges.

In the final case - is place between a-z and A-Z since both the characters surrounding the -(the one which we want to treat literally) that is z and A are already involved in ranges, the - is treated literally again.

Of all the mentioned methods, the escaping method is recommended as it makes your code easier to read and understand. Anyone seeing the \ would expect that an escape is intended. Placing the - at the beginning(end) will create problems if you later add a character before(after) it in the character class without escaping the - thus forming a range.

like image 133
codaddict Avatar answered Nov 09 '22 22:11

codaddict