开发者

Ruby: Conditional replace in String using gsub

Given an input string:

<m>1</m>
<m>2</m>
<m>10</m>
<m>11</m>

I would like to replace all values that are not equal to 1 with 5.

So the output String should look like:

<m>1</m>
<m>5</m>
<m>5</m>
<m>5</m>

I tried using:

gsub(/(<m>)([^1])(<\/m>)开发者_运维知识库/, '\15\3')

But this will not replace 10 and 11.


#gsub can optionally take a block and will replace with the result of that block:

subject.gsub(/\d+/) { |m| m == '1' ? m : '5' }


Without regexp just because it's possible

"1 2 10 11".split.map{|n| n=='1' ? n : '5'}.join(' ')


result = subject.gsub(/\b(?!1\b)\d+/, '5')

Explanation:

\b    # match at a word boundary (in this case, at the start of a number)
(?!   # assert that it's not possible to match
 1    # 1
 \b   # if followed by a word boundary (= end of the number)
)     # end of lookahead assertion
\d+   # match any (integer) number

Edit:

If you just wish to replace numbers that are surrounded by <m> and </m> then you can use

result = subject.gsub(/<m>(?!1\b)\d+<\/m>/, '<m>5</m>')
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜