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.
-
2In which parts do you want to match punctuation? What have you tried? Also, do you have any sample inputs?Wiseguy– Wiseguy2011-08-29 17:22:46 +00:00Commented Aug 29, 2011 at 17:22
-
Why don't you just add the (escaped) punctuation characters inside of the brackets?Blazemonger– Blazemonger2011-08-29 17:26:22 +00:00Commented Aug 29, 2011 at 17:26
-
Well, the expression has no punctuation characters... of course it cannot work. Great source for learning regular expressions: regular-expressions.infoFelix Kling– Felix Kling2011-08-29 17:27:06 +00:00Commented Aug 29, 2011 at 17:27
3 Answers
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
4 Comments
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.