Reputation: 21
I want a regular expression that prevents white spaces and only allows letters and numbers with punctuation marks(Spanish). The regex below works great, but it doesn't allow punctuation marks.
^[a-zA-Z0-9_]+( [a-zA-Z0-9_]+)*$
For example, when using this regular expression "Hola como estas" is fine, but "Hola, como estás?" does not match.
How can I tweak it to punctuation marks?
Upvotes: 2
Views: 1949
Reputation: 18641
Use \W+
instead of space and add \W*
at the end:
/^[a-zA-Z0-9_]+(?:\W+[a-zA-Z0-9_]+)*\W*$/
See proof
EXPLANATION
EXPLANATION
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
[a-zA-Z0-9_]+ any character of: 'a' to 'z', 'A' to 'Z',
'0' to '9', '_' (1 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
(?: group, but do not capture (0 or more times
(matching the most amount possible)):
--------------------------------------------------------------------------------
\W+ non-word characters (all but a-z, A-Z, 0-
9, _) (1 or more times (matching the
most amount possible))
--------------------------------------------------------------------------------
[a-zA-Z0-9_]+ any character of: 'a' to 'z', 'A' to
'Z', '0' to '9', '_' (1 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
)* end of grouping
--------------------------------------------------------------------------------
\W* non-word characters (all but a-z, A-Z, 0-
9, _) (0 or more times (matching the most
amount possible))
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string
Upvotes: 3