0

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.

ekad
  • 14,436
  • 26
  • 44
  • 46
Main Js
  • 9
  • 2
  • 1
    Welcome to SO! Please provide some (more) code so that we might be able to help you out - otherwise: it depends... – Jan Sep 07 '17 at 18:03
  • I would just leave it as is or change it to `(^|\s)#([\w]+)(?!\S)` –  Sep 07 '17 at 18:20

1 Answers1

0

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.