# Linking text with regex

**URL:** <https://www.ruby-forum.com/t/linking-text-with-regex/173503>\
**Category:** Ruby\
**Created:** [August 10, 2009, 5:13pm UTC](https://www.ruby-forum.com/t/linking-text-with-regex/173503 "2009-08-10T17:13:58Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![peterbe](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/bc79bd/32.png) [@peterbe](https://www.ruby-forum.com/u/peterbe)\
**Post date:** [August 10, 2009, 5:13pm UTC](https://www.ruby-forum.com/t/linking-text-with-regex/173503/1 "2009-08-10T17:13:58Z")

</div>

Hi

This is probably a silly question, but I’m wondering what the best way  
is to scan a string for regular expression matches, and then link to it.  
It would be great to do it in one line, like this:

```
<% text.sub!(/#[-'A-Za-z]+/, link_to($&, tweet.category_name))%>

```

But as the sub! has not completed, $& still refers to the old variable.  
I suppose I can just find the text I will be matching ahead of time,  
which would involve scanning the string twice, but there might be a  
better way. Thoughts?

Thanks in advance!!  
–Peter

---

<div class="post-metadata">

**Author:** ![peterbe](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/bc79bd/32.png) [@peterbe](https://www.ruby-forum.com/u/peterbe)\
**Post date:** [August 10, 2009, 7:02pm UTC](https://www.ruby-forum.com/t/linking-text-with-regex/173503/2 "2009-08-10T19:02:37Z")

</div>

On Mon, Aug 10, 2009 at 11:14 AM, Peter E.[removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
wrote:

> which would involve scanning the string twice, but there might be a  
> better way. Thoughts?

text.sub!(/#[-'A-Za-z]+/) {|m| link\_to(m, tweet.category\_name))}

–  
Rick DeNatale

Blog: [http://talklikeaduck.denhaven2.com/](http://talklikeaduck.denhaven2.com/)  
Twitter: [http://twitter.com/RickDeNatale](http://twitter.com/RickDeNatale)  
WWR: [http://www.workingwithrails.com/person/9021-rick-denatale](http://www.workingwithrails.com/person/9021-rick-denatale)  
LinkedIn: [http://www.linkedin.com/in/rickdenatale](http://www.linkedin.com/in/rickdenatale)

---

<div class="post-metadata">

**Author:** ![peterbe](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/bc79bd/32.png) [@peterbe](https://www.ruby-forum.com/u/peterbe)\
**Post date:** [August 10, 2009, 8:35pm UTC](https://www.ruby-forum.com/t/linking-text-with-regex/173503/3 "2009-08-10T20:35:02Z")

</div>

aha! This works great!

One further question - is there a best way to link the second and first  
occurrences of the string differently? The only way I can think of is  
with an index and a conditional in the block, but that just seems awful.

Thanks!
