joao-m-santos
joao-m-santos

Reputation: 187

Regex expression only matching the first occurrance

I'm trying to match all @mentions and #hashtags on a String using this RegEx expression:

(^|\s)([#@][a-z\d-]+)

According to regex101.com, since the + is there it should match all occurances

"+" Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed

But when I run it through a String with more than one occurrance, it only matches the first.

What's going on?

Thanks for your attention.

Upvotes: 0

Views: 62

Answers (2)

Rupesh Bramhankar
Rupesh Bramhankar

Reputation: 166

^ this symbol defines beginning of string. That is why it only match with first string.

Use /[@#]\w+/ regex.

Upvotes: 1

Jeremy Thille
Jeremy Thille

Reputation: 26360

Add the g (global) flag at the end for multiple matches.

/(^|\s)([#@][a-z\d-]+)/g

Upvotes: 2

Related Questions