Are there JavaScript equivalents of the Vim regular expression start and end of word atoms "\<" and "\>"?
Asked Answered
B

1

5

I know most regular expression engines, including the one in JavaScript have \b to match a word boundary, be it at either the start or end of a word.

But Vim also has two more specific regular expression atoms:

Does JavaScript have an equivalent to these atoms, and if not is there a way to express their more precise semantics some other way?

Byroad answered 19/11, 2012 at 12:15 Comment(3)
Actually I just started to worry that \< and \> are actually from Vim... maybe they're from both. Checking now...Byroad
But won't any word boundary be both the start of some word and the end of another word? What is the distinction you're trying to handle?Sidewalk
@MarkReed, no, because a word boundary does match only the position directly before/after a word and NOT e.g. the whitespace before/after the word.Fussbudget
F
7

As far as I know there is nothing predefined. But what you can do is, to add a lookahead to the word boundary, to check if it is the start or the end of the word.

\< would be then \b(?=\w). This checks if after the word boundary a word character is following ==> start of the word. See this as example on regexr

\> would be then \b(?!\w). This checks if after the word boundary not a word character is following ==> end of the word

Fussbudget answered 19/11, 2012 at 12:24 Comment(3)
+1, but you should use (?!\w) instead of (?=\W) for the second case.Janettjanetta
It's actually not just more clear - your solution would not have matched a word boundary at the end of the string.Janettjanetta
@Jan-StefanJanetzky Uh, no. Just (?!\w). Or (?=\W|$), but that's awkward.Janettjanetta

© 2022 - 2024 — McMap. All rights reserved.