ruby-on-rails - 删除特定标签内的内容

标签 ruby-on-rails regex

使用 Rails 3.2。我想删除 <b> 中的所有文本和标签,但我设法找到只剥离标签的方法。:

string = "
  <p>
    <b>Section 1</b>
    Everything is good.<br>
    <b>Section 2</b>
    All is well.
  </p>"
string.strip_tags
# => "Section 1 Everthing is good. Section 2 All is well."

我想实现这一目标:
"Everthing is good. All is well."

我也应该添加正则表达式匹配吗?

最佳答案

“正确”的方法是使用像 Nokogiri 这样的 html 解析器。 .
但是,对于这个简单的任务,您可以使用正则表达式。这很简单:
搜索:(?m)<b\s*>.*?<\/b\s*>并将其替换为空字符串。之后,使用 strip_tags .

正则表达式解释:

(?m)    # set the m modifier to match newlines with dots .
<b      # match <b
\s*     # match a whitespace zero or more times
>       # match >
.*?     # match anything ungreedy until </b found
<\/b    # match </b
\s*     # match a whitespace zero or more times
>       # match >

Online demo

关于ruby-on-rails - 删除特定标签内的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19637194/

相关文章:

java - 包含 0 和 4-9(4 ,5,6,7,8,9) 的字符串的正则表达式模式

javascript - 使用正则表达式每 n 行分割一个字符串

java - 用于以版本格式提取数字的正则表达式

javascript - 在 JS 中使用修改后的正则表达式匹配并替换正则表达式

javascript - ruby 哈希到 javascript 哈希

javascript - sketch.js 仅在 iPhone 上刷新后才有效

ruby-on-rails - rails 4 中 "find_all_by_id"的等价物是什么

ruby-on-rails - Rails的api方式如何防止XSS攻击?

ruby-on-rails - 未初始化的常量 Twitter::OAuth - 忽略某个地方的需求?

Java string.replaceAll() 无法将\R 识别为字符类的一部分