How to represent one space in a group of square brackets

I am facing the problem of representing a single space in a character set expression []. I ended up using something like this

([a-zA-Z0-9]|\x20)+ 

which I think is not very elegant

Update : Now I know what happens to my regex. I used something like this that didn't work

 [A-Za-z0-9/.,':!?$%()- ]+ 

But when I move the space to be after 9, like this

 [A-Za-z0-9 /.,':!?$%()-]+ 

And it works, just weird. I am trying this with the RegExr online regular expression tester .

Update 2 : I realized that the problem is that - inside the regular expression is used to represent the range in [] therefore, everything before and after has a different meaning than just a character

+7
source share
2 answers
 [a-zA-Z0-9 ] 

will add a space to the character class. I assume that you already know this, and you want to make sure that there will be only separate spaces in your line. In this case, you need additional viewing:

 ^(?!.* )[a-zA-Z0-9 ]*$ 

matches a string containing alphanumeric characters and spaces, but only individual spaces.

+15
source

You can just use a space.

For the regex structure in the question:

  ([a-zA-Z0-9]| )+ 

On practice:

 [a-zA-Z0-9 ]+ 
+7
source

All Articles