1

Let's say I've got some text with a couple tags like this:

[twitter:jpunt]

I want to replace those into something like this:

<a href="http://twitter.com/jpunt">@Jpunt</a>

How could I do this in Ruby? I've been researching regular expressions for a couple of hours, just with a lot of frustration as a result. Anyone?

1
  • You don't need a regulare expression to replace a constant. Just search and replace. Commented Jul 20, 2012 at 20:42

2 Answers 2

1

This should do the job:

initial = "[twitter:jpunt]"
link = initial.gsub(/\[twitter:(\w+)\]/i, '<a href="http://twitter.com/\1">@\1</a>')
Sign up to request clarification or add additional context in comments.

2 Comments

I can't see what's wrong with this answer. The only thing it doesn't do is capitalize the handle. Which I don't think it should, anyway. So +1 from me :)
Capitalizing the handle wasn't the point indeed. Thanks for your answer!
0

It is one line code (click here to test this code) >>

output = input.gsub(/\[([^:]+):([^\]]+)\]/) {
  '<a href="http://' + $1 + '.com/' + $2 + '">@' + $2.capitalize + '</a>' }

The above code works with any tag name. If you want just twitter to be allowed, then go with modification:

output = input.gsub(/\[twitter:([^\]]+)\]/) {
  '<a href="http://twitter.com/' + $1 + '">@' + $1.capitalize + '</a>' }

1 Comment

Thank you so much for the thorough example. Out of all things in tech, regexp is the thing I shutdown every time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.