Regex replace expression in Ruby on Rails -


I need to change some text in a DB area based on a regex search on the string.

So far, I have this:

  foo = my_string.gsub (/ \ [0-9 \] /, "replacement" + array [#] + "Text")   

Therefore, I am searching for each number in the field surrounded by brackets ([1], [2], etc.) What I would like to do is find each The number (within brackets) is found, and that number is used to find a specific array node.

Any thoughts? I know that someone needs some kind of explanation.

The easiest way is to use the block type:

  foo = My_string.gsub (/ \ [(\ d +) \] /) {array [$ 1.to_i]}   

and note that inside the Regex capture group inside the block , Global $ 1 which matches the first Capture group.

You can also use named capturing group, but there will be a separate global requirement for this because to get the existing MatchData inside the $ ~ block The only way is (AFAIK):

  foo = my_string.gsub (/ \ [(? & Lt; num & gt; \ d +) \] /) {| M A [$ ~ [: num] .to_i]}   

For example:

  & gt; & Gt; S = 'Where is [0] is [1] Pancakes [2] Home?' = & Gt; "Where is [0] [1] pancakes [2] home?" & Gt; & Gt; A =% w {a b c} = & gt; ["A", "b", "c"]> & gt; S.gsub (/ \ [(\ d +) \] /) {single [$ 1.to_i]} = & gt; "Where is the b-pancakes c home?" & Gt; & Gt; S.gsub (/ \ [(? & Lt; num & gt; \ d +) \] /) {| M A [$ ~ [: number] .to_i]} => "Where is the b-pancakes c home?"    

Comments

Popular posts from this blog

mysql - BLOB/TEXT column 'value' used in key specification without a key length -

memcached - Django cache performance -

java : convert string value to int -