0

I know this must be super simple but ...trying to match 2 use cases:

it can match this (exact)

var re = new RegExp("\\b" + name + "\\b");

or match this (same as above but MUST start with a space)

var re = new RegExp("^ \\b" + name + "\\b");


Actually the problem is that the string can contain multiple entries seperated by spaces like this

" somevar1 somevar2 somevar3 "

So when we pass name to the regex above we want it to match either at the beginning of the string with a space or at the beginning without space ..when we are not matching the beginning of the string (the rest), we do not test for a leading space

basically this "^ \\b" + name + "\\b|\\b" + name + "\\b"

Robert Hoffmann
  • 2,366
  • 19
  • 29

3 Answers3

1

Not sure why your first regex does not work for both cases. But I guess this is what you are looking for:

"(^ )?\\b" + name + "\\b"
ahoereth
  • 487
  • 1
  • 6
  • 13
1

Ok, you can use this pattern:

new RegExp("(?:^ |\\b)" + name + "\\b");

details:

(?:       # non capturing group
    ^[ ]  # start of the string followed by a space
  |       # OR
    \\b   # word boundary
)         # close the non capturing group

Here you have the choice between the start of the string with a space and a word boundary (that can be, for example .name or #name or name)

with " ?\\b" + name, since the space is optional, you can have name at the start of the string.

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
  • Thanks but i got my code mixed up ! :) What works for my particular code is actually ``" ?\\b" + name + "\\b"`` but ``"\s?\\b" + name + "\\b"`` does not ..what's the difference ? i thought \s is space ? – Robert Hoffmann Nov 12 '13 at 22:25
  • thanks again for the details. however isn't ``"\s?\\b" + name + "\\b"`` the same as ``" ?\\b" + name + "\\b"``. I'd say yes, but in my code they both behave differently – Robert Hoffmann Nov 12 '13 at 23:05
0

i guess you need something like this:

new RegExp("^ ?\\b" + name + "\\b");

or like this:

new RegExp("^ *\\b" + name + "\\b");
micnic
  • 10,915
  • 5
  • 44
  • 55