1

I want to replace all dashes that are inside square brackets but leave the ones that aren't.

String: dont-change-this[only-change-inside-brackets]

Result: dont-change-this[only_change_inside_brackets]

The way I'm currently doing it is by capturing everything in the square brackets and then replacing.

regex = /(\[([a-z-]+)\])/
testString = "dont-change-this[only-change-inside-brackets]"

testString.match regex
testString.sub(regex, $1.gsub(/-/, '_'))

It works, but I was wondering if there is a way to do this in just one expression.

2 Answers 2

5

You can use sub (or gsub) with a block:

my_string.sub(/\[.*?\]/){|x|x.tr('-','_')}
Sign up to request clarification or add additional context in comments.

Comments

0

Its a suggestion and i dont think its an ideal way, but you can actually split the sentence and then match the second element of the array returned.

2.0.0p247 :079 > str = "dont-change-this[only-change-inside-brackets]"
=> "dont-change-this[only-change-inside-brackets]"
2.0.0p247 :080 > s = str.split("[")
=> ["dont-change-this", "only-change-inside-brackets]"] 
2.0.0p247 :081 > s[1].gsub(/-/, '_')
=> "only_change_inside_brackets]" 

Comments

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.