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.
Asked
Active
Viewed 5.7k times
21

Tim Pietzcker
- 328,213
- 58
- 503
- 561

jdimona
- 1,227
- 2
- 9
- 9
-
2In which parts do you want to match punctuation? What have you tried? Also, do you have any sample inputs? – Wiseguy Aug 29 '11 at 17:22
-
Why don't you just add the (escaped) punctuation characters inside of the brackets? – Blazemonger Aug 29 '11 at 17:26
-
Well, the expression has no punctuation characters... of course it cannot work. Great source for learning regular expressions: http://www.regular-expressions.info/ – Felix Kling Aug 29 '11 at 17:27
3 Answers
38
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

CaNNaDaRk
- 1,302
- 12
- 20
-
-
You mean like this (Javascript ahead)? var rgx = /[A-Za-z0-9 _.,!"'/$]*/; rgx.test("testme"); Or like this: /[A-Za-z0-9 _.,!"'/$]*/.test("testme") – CaNNaDaRk Jun 13 '14 at 12:33
-
I just tried this var r = /[A-Za-z0-9 _.,!"'/$]*/ r.test('¬¬'); returns true? Am I missing something – Fred Johnson Mar 09 '15 at 09:46
-
It returns true because it matches an empty string. While the regex ends with a * (which means "match 0 or many") it evaluates to true because it doesn't find any of the given characters. Test function will evaluate to false only if you change that "*" with a "+" (which means 1..many) like this: /[A-Za-z0-9 _.,!\"\'\/$]+/ (just try exec method instead of test and see what it matches) – CaNNaDaRk Mar 10 '15 at 17:00
2
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.

Tim Pietzcker
- 328,213
- 58
- 503
- 561
1
<script type="text/javascript">
check("hello dfdf asdjfnbusaobfdoad fsdihfishadio fhsdhf iohdhf");
function check(data){
var patren=/^[A-Za-z0-9\s]+$/;
if(!(patren.test(data))) {
alert('Input is not alphanumeric');
return false;
}
alert(data + " is good");
}
</script>

Tarun Gupta
- 6,305
- 2
- 42
- 39