Kobius
Kobius

Reputation: 714

Regex for finding Instagram-style hashtag in string - Ruby

I'm struggling to build a regex in Ruby to be able to wrap hashtags from a string in some HTML.

Here's what I have so far:

description.gsub!(/#\w+/, '[#\1]')

This should be a regex to pick up hashtags that contain letters, numbers and underscores - and be split on anything other than these, such as a space or HTML tag.

This should input:

hello there #obiwan

and output:

hello there [#obiwan]

But currently it outputs:

hello there [#]

Any ideas as to why?

Upvotes: 0

Views: 64

Answers (1)

The fourth bird
The fourth bird

Reputation: 163642

If you want to refer to a capture group, you can use \\1 but in the current pattern there is no group.

You can add a capture group in the pattern:

description.gsub(/#(\w+)/, '#[\\1]')

Or use the full match in the replacement:

description.gsub(/#\w+/, '[\\0]')

Upvotes: 2

Related Questions