I want to validate that the characters are alpha numeric:
Regex aNum = Regex("[a-z][A-Z][0-9]");
I want to add the option that there might be a white space, so it would be a two word expression:
Regex aNum = Regex("[a-z][A-Z][0-9]["\\s]");
but couldn't find the correct syntax.
id applicate any incite.
Spaces can be found simply by putting a space character in your regex. Whitespace can be found with \s . If you want to find whitespace between words, use the \b word boundary marker.
The most common regex character to find whitespaces are \s and \s+ . The difference between these regex characters is that \s represents a single whitespace character while \s+ represents multiple whitespaces in a string.
The replaceAll() method accepts a string and a regular expression replaces the matched characters with the given string. To remove all the white spaces from an input string, invoke the replaceAll() method on it bypassing the above mentioned regular expression and an empty string as inputs.
[A-Za-z0-9\s]{1,}
should work for you. It matches any string which contains alphanumeric or whitespace characters and is at least one char long. If you accept underscores, too you shorten it to [\w\s]{1,}
.
You should add ^ and $ to verify the whole string matches and not only a part of the string:
^[A-Za-z0-9\s]{1,}$
or ^[\w\s]{1,}$
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With