I'm trying to write a very simple regex to find all words in a string that start with the symbol @
. Then change the word to a link. Like you would see in a Twitter where you can mention other usernames.
So far I have written this
def username_link(s)
s.gsub(/\@\w+/, "<a href='/username'>username</a>").html_safe
end
I know it's very basic and not much, but I'd rather write it on my own right now, to fully understand it, before searching GitHub to find a more complex one.
What I'm trying to find out is how can I reference that matched word and include it in the place of username
. Once I can do that i can easily strip the first character, @
, out of it.
Thanks.
You can capture using parentheses and backreference with \\1
(and \\2
, and so on):
def username_link(s)
s.gsub(/@(\w+)/, "<a href='/\\1'>\\1</a>").html_safe
end
See also this answer
You should use gsub
with back references:
str = "I know it's very basic and not much, but @tim I'd rather write it on my own."
def username_to_link(str)
str.gsub(/\@(\w+)/, '<a href="\1">@\1</a>')
end
puts username_to_link(str)
#=> I know it's very basic and not much, but <a href="tim">@tim</a> I'd rather write it on my own.
Following Regex should handle corner cases which other answers ignore
def auto_username_link(s)
s.gsub(/(^|\s)\@(\w+)($|\s)/, "\\1<a href='/\\2'>\\2</a>\\3").html_safe
end
It should ignore strings like "someone@company" or "@username-1" while converting everything like "Hello @username rest of message"
How about this:
def convert_names_to_links(str)
str = " " + str
result = str.gsub(
/
(?<=\W) #Look for a non-word character(space/punctuation/etc.) preceeding
@ #an "@" character, followed by
(\w+) #a word character, one or more times
/xm, #Standard normalizing flags
'<a href="/\1">@\1</a>'
)
result[1..-1]
end
my_str = "@tim @tim @tim, @@tim,@tim t@mmy?"
puts convert_names_to_links(my_str)
--output:--
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.