gkaykck
gkaykck

Reputation: 2367

Catching a string like #.+# with regex

I am building a project which users should be able to generate links easily by putting: #this is the link#. And i am trying to catch strings in between 2 # symbols with regex. I have tried,

#.+#

it works perfectly if only 1 link in users string, but if there are more than 1 links like,

#asdfasdf asdf# asdf asfasdfasdf asd fasd fasdf #asdfasdf asdfasdf asdf asdf#

it catches the whole string. But i need them separately, so i can substitute them with tags.

Upvotes: 0

Views: 58

Answers (2)

SwiftMango
SwiftMango

Reputation: 15284

Use non-greedy match

#.+?#

It will catch indivisual ones.

Upvotes: 2

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230306

This is called "greedy regex". By default regular expression matches the longest string possible. You can make it non-greedy this way:

/#.+?#/

Demo: http://rubular.com/r/7WWyaUApFt

Upvotes: 4

Related Questions