正则表达式部分找到单词的问题

时间:2016-09-11 19:38:42

标签: ruby regex rubular

我有一个正则表达式,但不是全部:

str.scan(/typeaheadResult\(\{\"Q\":("\w+\s?\w+\s?\w+\s?\w+"),\"R\":\[+("\w+\s?\w+\s?\w+\s?\w+")/)

似乎没有捕获的字符串如下:

if (typeof typeaheadResult !== "undefined") { typeaheadResult({"Q":"crapshoot","R":[]}) }

我的正则表达式对上面的字符串不起作用,我认为这不是因为使用了不恰当的单词。 以下是我尝试的内容的永久链接:http://rubular.com/r/WOr7xYPePs 它有其余的样本字符串,这很重要。

2 个答案:

答案 0 :(得分:0)

R:[之后的部分必须在\w之间包含至少4个"个字符。

如果它是可选的,您必须添加?

<强>更新

只需在正则表达式末尾添加?即可解决问题:http://rubular.com/r/HUmtoffTmi

答案 1 :(得分:0)

我假设每个段落最多只有一个匹配项,并且对于给定段落中的匹配项,"[]"跟在"R:之后或"Q":"之后的字符串和以下一个双引号前面的字符结尾,以"R":[["后面的字符串开头,以下一个双引号前面的字符结束。

str =<<BITTER_END
\if (typeof typeaheadResult !== "undefined") { typeaheadResult({"Q":"standing desk Mike","R":[["standing desk",[["Home",4044]]],"standing desk converter","adjustable standing desk","standing desk 48","tabletop standing desk","glass standing desk desk"]}) }

if (typeof typeaheadResult !== "undefined") { typeaheadResult({"Q":"laptop bag","R":[["laptop bag",[["Electronics",3944]]],"laptop bags for 15.6 inch laptops","laptop bags for women","laptop bag 15.6","laptop bags for 17.3 in laptops","rolling laptop bag","laptop bag with wheels","laptop bag 17\""]}) }

\if (typeof typeaheadResult !== "undefined") { typeaheadResult({"Q":"sitting desk Melba","R":[["standing desk",[["Home",4044]]],"standing desk converter","adjustable standing desk","standing desk 48","tabletop standing desk","glass standing desk desk"]}) }

if (typeof typeaheadResult !== "undefined") { typeaheadResult({"Q":"crapshoot hello","R":[]}) }
BITTER_END

r = /
    typeaheadResult\(\{\"Q\":\" # match 'typeaheadResult({"Q":"'
    ([[[:alnum:]]\s]+)   # match letters, digits and spaces in capture group 1
    \",\"R\":            # match string
    (?:                  # begin non-capture group
      \[\[\"             # match 2 left brackets and a double quote
      ([[[:alnum:]]\s]+) # match > 0 letters, digits and spaces in capture group 2
      |                  # or
      (\[\])             # match left then right bracket in capture group 3
    )                    # end non-capture group
    /x                   # free-spacing regex definition mode

str.split(/\n\n+/).map do |s|
  ss = s[r]
  ss = nil unless (($2 && $1 =~ /\A#{$2}/) || $3=="[]")
  ss
end.compact
  #=> ["typeaheadResult({\"Q\":\"standing desk Mike\",\"R\":[[\"standing desk",
  #    "typeaheadResult({\"Q\":\"laptop bag\",\"R\":[[\"laptop bag",
  #    "typeaheadResult({\"Q\":\"crapshoot hello\",\"R\":[]"] 

如果$2不是nil$1.begins_with($2)false,您可以考虑标记可能的错误数据。