Is (^|\s) valid regex in JavaScript?

96 views Asked by At

Is it recommendable to use anchors inside capturing groups? I am trying to simulate lookbehind operation with that pattern to match line start or whitespace.

For example to match hashtags which are in beginning of the line or after whitespace AND they will end the line or there is whitespace after them, is there better way to do it than this?

(^|\s)#([\w]+)($|\s)

I left non capturing groups for the sake of simplicity.

1

There are 1 answers

0
AudioBubble On

In your case (^|\s) is needed inside the group because it is used within alternations.
It says BOS or whitespace, but not both.

Fwiw, (^|\s) is a typical whitespace boundary, which doesn't require a group.
It is this equivalent (?<!\S).

But JS doesn't support look behind assertions, so you'd have to leave that.

For the other side (\s|$) it would be (?!\S) which uses a look ahead assertion, which JS supports.