Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex check for white space in middle of string

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.

like image 895
eran otzap Avatar asked Apr 03 '11 17:04

eran otzap


People also ask

How do you find a space in a string in regex?

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.

What is the regex for white space?

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.

How do I get rid of white space in regex?

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.


1 Answers

[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,}$.

like image 55
Zebi Avatar answered Oct 06 '22 05:10

Zebi