[SOLVED] Best RegEx option to target a space?

What do you guys use when you want to target/match a space (without including tab, new line, etc?). I used \s sometimes, but what if I just want the space?

I saw somewhere online someone suggesting " " so something like this, for example:
[^a-zA-Z0-9" "]

I don't think I understand what you're trying to do, as the regex to match just a space is simply, well, a space :).

image

You must mean something other than what I think you mean? And as written, your regex is set to find anything that's not one of the listed characters (the leading carat negates the class), including quotes (twice) and a space:

image

-rob.

1 Like

Yes for that particular case I want to keep all letters, numbers, and spaces.
For this macro, I'm replacing everything else with a dash.

The thing I see with just adding a space, is that visually speaking, can be a bit misleading, whereas adding " " shows that there's something there, for example:
[^a-zA-Z0-9" "]
versus
[^a-zA-Z0-9 ]

Maybe it's just me, but if I have this [^a-zA-Z0-9 ] I could instantly think that the space was a typo and just remove it, you know?
At the same time, if I see this
[^a-zA-Z0-9" "]
I probably won't think that the space between the quotes is a typo, because "" would probably don't mean anything.

But I saw this suggestion on a forum about PHP or Javascript, so maybe that's why they suggested the quotes. I can see now that adding " " is also negating the quotes. Thanks for pointing that out.

So basically I just use a normal space or, if I know I won't need tab, etc, I can just use \s to make it more visual, right?

If you put quotes inside the character class brackets, then regex will look for quotes in your string. The only sort of delimiter it knows about is the backslash, for when you need to include a character that otherwise has meaning inside regex, i.e. \(.

Yep, anything you put in the brackets will be negated.

Yes, mostly. It also matches line breaks and some obscure characters that shouldn't be an issue (form feeds and vertical whitespace, whatever that might be).

-rob.

1 Like

In this case I thought that the double quotes were not evaluated as characters, but more like a way to say "what's inside the quotes", in this case, the space.
But I understand it now. Thanks!

You can use a backslash to quote any character you want, if you want it to stand out a bit from the rest:

[^a-zA-Z0-9\ ]

-rob.

2 Likes

Good tip! Yes, that helps for sure