Ruby: Conditional replacement in String with gsub

Given the input line:

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

I would like to replace all values โ€‹โ€‹that are not equal 1to 5.
Thus, the output line should look like this:

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

I tried using:

gsub(/(<m>)([^1])(<\/m>)/, '\15\3')

But this does not replace 10and 11.

+3
source share
3 answers

#gsub may optionally take a block and replace it with the result:

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

Without regex just because itโ€™s possible

"1 2 10 11".split.map{|n| n=='1' ? n : '5'}.join(' ')
+4
source
result = subject.gsub(/\b(?!1\b)\d+/, '5')

:

\b    # match at a word boundary (in this case, at the start of a number)
(?!   # assert that it 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:

, <m> </m>,

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

Source: https://habr.com/ru/post/1778740/


All Articles