Reputation: 1342
I would like to replace text inside of brackets, and that has a colon
and a u
.
For example, Here is a link [u:person]!
would become Here is a link <a href="/user/person">Person</a>!
I am not very experienced with regex, and I am having problems with \1
and $1
Here is the regex that I am using now:
string.gsub(/\[(\w*).*?\]/, "<a href='/user/\1'>\1</a>")
Upvotes: 4
Views: 1687
Reputation: 23616
You could use a regex like this:
/\[u\:([\S]+)\]/
and replace it with:
<a href='/user/#{$1}'>#{$1}</a>
Here's a breakdown of what it the regex does:
\[
, which is just the literal [
characteru
and \:
, which are the literal u
and :
character respectively([\S])
. The parentheses make a capturing group, which is what #{$1}
will be filled in with in the replace part of the regex. [\S]+
looks for all non-whitespace characters.\]
, which is just the literal ]
character.Your code should look something like this:
string.gsub('/\[u\:([\S]+)\]/', '<a href='/user/#{$1}'>#{$1}</a>')
Here is a live test of the regex: https://regex101.com/r/vK0iO2
Upvotes: 0
Reputation: 12558
I changed your regular expression to this, so that person
is captured:
/\[\w*:(.*?)\]/
And then replaced it with this String:
"<a href=\"/user/#{$1}\">#{$1.capitalize}</a>"
You were close with $1
, it just needs to be evaluated as Ruby (using String interpolation, inside a block):
string.gsub(/\[\w*:(.*?)\]/) { "<a href=\"/user/#{$1}\">#{$1.capitalize}</a>" }
Upvotes: 1
Reputation: 122463
Make the regex /\[\w*:(.*?)\]/
so that person
can be captured instead of u
. Then use a single quoted string so that \1
isn't interpreted as \x01
.
str = "Here is a link [u:person]!"
puts str.gsub(/\[\w*:(.*?)\]/, '<a href="/user/\1">\1</a>')
# => Here is a link <a href="/user/person">person</a>!
Upvotes: 1
Reputation: 67988
\[[^\]]*u:([^\]]*)\]
Try this.Replace by <a href='/user/\1'>\1</a>
.See demo.
https://regex101.com/r/gX5qF3/13
Upvotes: 0