0

I'm matching words with regex in javascript. The following expression uses whitespace to separate the potential matches:

/(\W)(foo)(\W)/g

This works most of the time, but it fails when there are two matches separated by a single space. (e.g. "foo foo") I think this is because the space that separates them is the last \W of the first match and the first of the second.

Is there any way to modify this expression to work in this edge case?

4

3 回答 3

3

You can use \b instead of \W. It matches a zero-width word boundary (a boundary between a \w and a \W or the start/end of the string, while \W matches a character which may not exist at the start or end of a string.

于 2012-05-19T15:42:34.673 回答
1

Javascript regexes have lookahead, so you can probably do something like this:

/(\W)(foo)(?=\W)/g

I don't think lookbehinds are available, but there are other techniques that have the same effect.

Of course, this is functionally different, in that the lookahead doesn't capture, so it depends on the nature of your problem. The main point here it not that it doesn't capture, but that it doesn't match; thereby avoiding your problem.

于 2012-05-20T15:23:08.383 回答
-2

Give this a try, I think it will work for you:

/(\W)(foo| )(\W)/g

This will tell the regex to match foo or whitespace between the two \Ws.

于 2012-05-19T15:48:14.657 回答