我有以下字符串,我想从中提取类值“ruby”,“html”,“java”。我的目标是理解/学习我一直害怕的正则表达式: - )。
<div class="ruby" name="ruby_doc">
<div class="html" name="html_doc">
<div class="java" name="java_doc">
这是我到目前为止所拥有的
str = <<END
<div class="ruby" name="ruby_doc">
<div class="html" name="html_doc">
<div class="java" name="java_doc">
END
str.scan(/"[^"]+/) #=> returns
["\"ruby", "\" name=", "\"ruby_doc", "\">\n<div class=", "\"html",...]
str.scan(/class="[^"]+/) #=> ["class=\"ruby", "class=\"html", "class=\"java"]
str.scan(/"(\w)+?"/) #=> [["ruby"], ["ruby_doc"], ["html"], ["html_doc"], ...]
答案 0 :(得分:4)
str.scan(/\b(?<=class=\")[^"]+(?=\")/)
# => ["ruby", "html", "java"]
答案 1 :(得分:3)
使用 Nokogiri
:
require 'nokogiri'
doc = Nokogiri::HTML::Document.parse <<-_html_
<div class="ruby" name="ruby_doc">
<div class="html" name="html_doc">
<div class="java" name="java_doc">
_html_
# to get values of class attribute
doc.xpath('//div/@class').map(&:to_s)
# => ["ruby", "html", "java"]
# to get values of name attribute
doc.xpath('//div/@name').map(&:to_s)
# => ["ruby_doc", "html_doc", "java_doc"]
答案 2 :(得分:2)
不建议使用正则表达式解析HTML。如果你必须编写一个有点正确的正则表达式,那么你可以试试
str.scan /<div\s+class=\s*"([^"]+)/
#=> [["ruby"], ["html"], ["java"]]
答案 3 :(得分:1)
根据@Arup的回答你真的应该使用Nokogiri。但是,如果你坚持......
str.scan(/(?:class\=\")(\w+)(?:\")/).flatten
2.0.0p247 :001 > str = <<END
2.0.0p247 :002"> <div class="ruby" name="ruby_doc">
2.0.0p247 :003"> <div class="html" name="html_doc">
2.0.0p247 :004"> <div class="java" name="java_doc">
2.0.0p247 :005"> END
=> "<div class=\"ruby\" name=\"ruby_doc\">\n<div class=\"html\" name=\"html_doc\">\n<div class=\"java\" name=\"java_doc\">\n"
2.0.0p247 :006 > str.scan(/(?:class\=\")(\w+)(?:\")/).flatten
=> ["ruby", "html", "java"]
答案 4 :(得分:-2)
Howsabout:
str.scan /"(.*?)"/
#=> [["ruby"], ["ruby_doc"], ["html"], ["html_doc"], ["java"], ["java_doc"]]