J.Luca
J.Luca

Reputation: 208

Improving a regex for the hashtag to generate a link

I'm using this Regular Expression

(^|\s)(#\w+)
To take this -> #test

#test <- to take this

to take this #test another word

to take this #Mest another word

To don't take this -> l'#09

to don't take this -> &#187; or &#39;

But I have a problem during the substitution.

I use this

$1<a href="/hash/$2" class='hash_tag'>$2</a>

But in this way I have the # also in the href.

For example

Take this <a href="/hash/#test" class='hash_tag'>test</a>

While, I have to obtain this

Take this <a href="/hash/test" class='hash_tag'>#test</a>

Any tips?

Do I need a third group? How to do?

Can I improve it?

https://regex101.com/r/6C1VDU/1

Upvotes: 1

Views: 47

Answers (2)

Ryszard Czech
Ryszard Czech

Reputation: 18611

Adding a third group is easy:

(^|\s)(#(\w+))
|__1_|| |   ||
      | |_3_||
      |____2_|

Replace with

$1<a href="/hash/$3" class='hash_tag'>$2</a>

See proof.

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You need to modify the regex and replacement:

Regex: (^|\s)#(\w+)
Replacement: $1<a href="/hash/$2" class='hash_tag'>#$2</a>

See the regex demo.

So, the # is left out of capturing group #2, and you only add it where you need in the replacement pattern.

Upvotes: 0

Related Questions