user1170330 user1170330 - 5 months ago 16
Javascript Question

Regex for finding substring

Suppose I have the following string "a b c".

With regex I want to find the substring " b" (please mind the space before the letter b).

When I do

[ b]
, it only find the space before b, but not the letter itself.
When I do
[ b]+
, it find b, but also the spaces before and after b. Same applies even for nonsense like
[ bbbbb ]+

What is the right expression for finding only " b"?

PS: I tested my regex here:


You can use ( b) to match for the space and b together (Note the parenthesis are optional depending if you are trying to match for it)

See this example.

Also, when you use [ b] it matches for a single character in the list (in this case a space and b) so it does not look to see if they are consecutive.

Edit: If you are looking to match a non-whitespace character instead of just a space, you can use \sb where \s is the token for a non-whitespace character.