kernification
kernification

Reputation: 523

Using wildcards in gsub

I would like to do something like this:

"String with text and $abc$ and $def$ and so on... ".gsub("$*$", "replaceText")

which results in

"String with text and replaceText and replaceText and so on... "

But I have no idea how wildcards like * work here.

Upvotes: 0

Views: 1281

Answers (3)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

Just out of curiosity: whether one has more delimiters (not the dollar sign only,) she might use back-references:

str = "String with text and $abc$ and *def* and so on... "
str.gsub(/(?<delim>[$*]).*?\k<delim>/, "replaceText")
#⇒ "String with text and replaceText and replaceText and so on... "

Note that inside [] there is no need to escape $ (* neither.)

Upvotes: 1

Sachin R
Sachin R

Reputation: 11876

"String with text and $abc$ and $def$ and so on... ".gsub(/\$\w+\$/, "replaceText")

Try \$\w+\$ in http://rubular.com/

http://rubular.com/r/ZbgdVQvDGb

Upvotes: 0

Deepak Mahakale
Deepak Mahakale

Reputation: 23671

You can use regex for this purpose

"String with text and $abc$ and $def$ and so on... ".gsub(/\$\w+\$/, "replaceText")
#=> "String with text and replaceText and replaceText and so on... "

Remember you will need to escape $

Upvotes: 4

Related Questions