Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A regex to match strings with alphanumeric, spaces and punctuation

Tags:

I need a regular expression to match strings that have letters, numbers, spaces and some simple punctuation (.,!"'/$). I have ^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$ and it works well for alphanumeric and spaces but not punctuation. Help is much appreciated.

like image 375
jdimona Avatar asked Aug 29 '11 17:08

jdimona


People also ask

How do you write alphanumeric in regex?

The regex \w is equivalent to [A-Za-z0-9_] , matches alphanumeric characters and underscore.

How do I check if a string is alphanumeric regex?

Considering you want to check for ASCII Alphanumeric characters, Try this: "^[a-zA-Z0-9]*$" . Use this RegEx in String. matches(Regex) , it will return true if the string is alphanumeric, else it will return false.

Does regex match dot space?

Yes, the dot regex matches whitespace characters when using Python's re module.

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).


2 Answers

Assuming from your regex that at least one alphanumeric character must be present in the string, then I'd suggest the following:

/^(?=.*[A-Z0-9])[\w.,!"'\/$ ]+$/i

The (?=.*[A-Z0-9]) lookahead checks for the presence of one ASCII letter or digit; the nest character class contains all ASCII alphanumerics including underscore (\w) and the rest of the punctuation characters you mentioned. The slash needs to be escaped because it's also used as a regex delimiter. The /i modifier makes the regex case-insensitive.

like image 23
Tim Pietzcker Avatar answered Sep 19 '22 15:09

Tim Pietzcker


Just add punctuation and other characters inside classes (inside the square brackets):

[A-Za-z0-9 _.,!"'/$]*

This matches every string containing spaces, _, alphanumerics, commas, !, ", $, ... Pay attention while adding some special characters, maybe you need to escape them: more info here

like image 102
CaNNaDaRk Avatar answered Sep 22 '22 15:09

CaNNaDaRk