我有一个几乎与“Ruby gsub multiple characters in string”相同的问题。
但是,我的字符串包含特殊字符:
a = "<p>text</p> <strong>bold</strong> and <em>italic</em>"
使用 /\w+/
对我不起作用。
我尝试了许多不同的组合,但没有成功。
我应该在下面输入什么 RegEx 匹配项才能使其正常工作?我想替换字符串中任何位置的匹配项。
顺便说一句,我正在使用 Rails。
我想要的匹配项是:
a.gsub({{WHAT REGEX EXP?}},
"\r\n" => "",
"<p>" => "",
"</p>" => "\n\n",
"<br />" => "\n",
"<strong>" => "*",
"</strong>" => "*",
"<em>" => "_",
"</em>" => "_",
"<s>" => "~",
"</s>" => "~",
"<blockquote>" => ">",
"</blockquote>" => ">",
"&" => "&",
"<" => "<",
">" => ">"
)
最佳答案
#gsub
有效:
replacements = {
"\r\n" => "",
"<p>" => "",
"</p>" => "\n\n",
"<br />" => "\n",
"<strong>" => "*",
"</strong>" => "*",
"<em>" => "_",
"</em>" => "_",
"<s>" => "~",
"</s>" => "~",
"<blockquote>" => ">",
"</blockquote>" => ">",
"&" => "&",
"<" => "<",
">" => ">"
}
a = "<p>text</p> <strong>bold</strong> and <em>italic</em>"
replacements.each do |find, replace|
a.gsub!(find, replace)
end
a # => "text\n\n *bold* and _italic_"
关于regex - 如何用特殊字符替换字符串中的多个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57226735/