简体   繁体   English

Ruby:使用gsub在String中进行条件替换

[英]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 . 我想用5替换所有不等于1值。
So the output String should look like: 所以输出String应如下所示:

<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 . 但这不会取代1011

#gsub可以选择一个块,并替换为该块的结果:

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

没有正则表达式只是因为它是可能的

"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 如果您只想替换<m></m>所包围的数字,那么您可以使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM