在导轨中的两个标记之间替换某个字符串?

时间:2015-03-23 04:46:27

标签: ruby-on-rails ruby regex gsub

我想替换" \ n"进入" br"代码标记之间的标记(在我的情况下是```)在插入DB之前(我正在处理textarea),例如:

```
echo "Hello";
echo "World!";
```

first line.
second line.

会变成:

```<br/>echo "Hello";<br/>echo "World!";<br/>```
first line .
second line . 

1 个答案:

答案 0 :(得分:0)

str = %q{
```
echo "Hello";
echo "World!";
```

first line.
second line.
}

pattern = %r{
  `{3}
  .*? 
  `{3}
}xm

str.gsub!(pattern) do |match|
  match.gsub!("\n", '<br/>')
end

puts str

--output:--

```<br/>echo "Hello";<br/>echo "World!";<br/>```

first line.
second line.