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
.
<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>')
精彩评论