Tim
Tim

Reputation: 6209

Simple Ruby Regex Question

I have a string in Ruby:

str = "<TAG1>Text 1<TAG1>Text 2"

I want to use gsub to get a string like this:

want = "<TAG2>Text 1</TAG2><TAG2>Text2</TAG2>"

In other words, I want to save everything in between a <TAG1> and EITHER: 1) the next occurrence of a "<", or 2) the end of the string.

The best regex i could come up with was:

regex = /<TAG1>(.*)(?:<|$)/

But the problem with this is that it'll just match the entire str, where what I want is both matches within str. (In other words, it seems like the end of string char ($) seems to have precedence over the "<" character--is there a way to flip it around?

Upvotes: 1

Views: 80

Answers (1)

Logan Capaldo
Logan Capaldo

Reputation: 40336

/<TAG1>([^<]*)/ will match that. If there's no < it'll go all the way to the end of the string. Otherwise it will stop when it hits a <. Your problem is that . matches < as well. An alternative way would be to do /<TAG1>(.*?)(?:<|$)/, which makes the * non-greedy.

Upvotes: 3

Related Questions