开发者

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 开发者_如何学Pythonoccurrence 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?


/<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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜