I want a regular expression that prevents symbols and only allows letters and numbers. The regex below works great, but it doesn't allow for spaces between words.
^[a-zA-Z0-9_]*$
For example, when using this regular expression "HelloWorld" is fine, but "Hello World" does not match.
How can I tweak it to allow spaces?
Just add a space to end of your regex pattern as follows:
I find this one works well for a "FullName":
One possibility would be to just add the space into you character class, like acheong87 suggested, this depends on how strict you are on your pattern, because this would also allow a string starting with 5 spaces, or strings consisting only of spaces.
The other possibility is to define a pattern:
I will use
\w
this is in most regex flavours the same than[a-zA-Z0-9_]
(in some it is Unicode based)This will allow a series of at least one word and the words are divided by spaces.
^
Match the start of the string\w+
Match a series of at least one word character( \w+)*
is a group that is repeated 0 or more times. In the group it expects a space followed by a series of at least one word character$
matches the end of the stringFor alphabets only:
For alphanumeric value and
_
:Had a good look at many of these supposed answers...
...and bupkis after scouring Stack Overflow as well as other sites for a regex that matches any string with no starting or trailing white-space and only a single space between strictly alpha character words.
Thus easily modified to alphanumeric:
(This does not match single words but just use a switch/if-else with a simple
^[a-zA-Z0-9]+$
if you need to catch single words in addition.)enjoy :D
Try this: (Python version)
change the upper limit based on your data set