Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx Pattern to Match Only Certain Characters

I'm a newbie to RegEx, and this particular issue is flummoxing me. This is for use with a JavaScript function.

I need to validate an input so that it matches only these criteria:

  • Letters A-Z (upper and lowercase)
  • Numbers 0-9
  • The following additional characters: space, period (.), comma (,), plus (+), and dash (-)

I can write a pattern easily enough for the first two criteria, but the third one is more difficult. This is the last pattern I managed, but it doesn't seem to work with the test string Farh%%$$+++,

Here's the pattern I'm trying

[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\\+\\.\\,\\s]*$  

It's failing in that it's letting characters other than those specified in the text field when submitting the form.

Any help would be greatly appreciated.

like image 505
RHPT Avatar asked Oct 12 '09 17:10

RHPT


People also ask

How do I match a specific character in regex?

Match any specific character in a setUse square brackets [] to match any characters in a set. Use \w to match any single alphanumeric character: 0-9 , a-z , A-Z , and _ (underscore). Use \d to match any single digit. Use \s to match any single whitespace character.

What is the regular expression matching one or more specific characters?

The character + in a regular expression means "match the preceding character one or more times". For example A+ matches one or more of character A. The plus character, used in a regular expression, is called a Kleene plus .

What does ?= Mean in regex?

?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).


2 Answers

I just tested this out, and it seems to work at least from my first round testing.

^[a-zA-Z 0-9\.\,\+\-]*$ 
like image 114
Mitchel Sellers Avatar answered Sep 19 '22 12:09

Mitchel Sellers


The dash needs to be first in order not to be interpreted as a range separator. Also, make sure you anchor your regex with a ^ and $ at the beginning and end respectively so that your entire test string gets swallowed by your regex.

/^[-+., A-Za-z0-9]+$/
like image 22
Asaph Avatar answered Sep 18 '22 12:09

Asaph