在Ruby中,可以使用正则表达式(Regex)来处理和转换字符串。HTML标记剥离是指从包含HTML代码的字符串中移除所有HTML标签,只保留纯文本内容。
以下是几种在Ruby中剥离HTML标记的方法:
def strip_html_tags(text)
text.gsub(/<[^>]*>/, '')
end
# 示例使用
html_string = "<p>Hello, <b>world</b>!</p>"
puts strip_html_tags(html_string) # 输出: Hello, world!
def strip_html_tags(text)
text.gsub(/<!--.*?-->|<[^>]+>/, '')
end
# 示例使用
html_string = "<!-- comment --><div>Text <span>with</span> tags</div>"
puts strip_html_tags(html_string) # 输出: Text with tags
虽然这不是正则表达式方法,但在实际应用中更推荐使用专门的HTML解析器:
require 'nokogiri'
def strip_html_tags(text)
Nokogiri::HTML(text).text
end
# 示例使用
html_string = "<script>alert('xss')</script><p>Safe text</p>"
puts strip_html_tags(html_string) # 输出: alert('xss')Safe text
虽然问题要求使用正则表达式,但在实际开发中,Nokogiri等HTML解析器更可靠,因为它们:
正则表达式方法适合简单的、受控环境下的HTML处理,但对于生产环境或安全敏感的应用,建议使用专门的HTML解析库。
没有搜到相关的文章