Home > Net >  Regex for finding Instagram-style hashtag in string - Ruby
Regex for finding Instagram-style hashtag in string - Ruby

Time:03-16

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?

CodePudding user response:

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]')
  • Related