Ruby正则表达式提取单词

Sha*_*abu 11 ruby regex string cpu-word

我正在努力想出一个正则表达式,它可以将一个字符串拆分成单词,其中单词被定义为由空格包围的字符序列,或者用双引号括起来.我正在使用String#scan

例如,字符串:

'   hello "my name" is    "Tom"'
Run Code Online (Sandbox Code Playgroud)

应该匹配的话:

hello
my name
is
Tom
Run Code Online (Sandbox Code Playgroud)

我设法匹配双引号括起来的单词:

/"([^\"]*)"/
Run Code Online (Sandbox Code Playgroud)

但是我无法弄清楚如何将空白字符包围起来以获得'你好','是'和'汤姆',同时又不会搞砸'我的名字'.

任何帮助都将不胜感激!

Nar*_*ala 22

result = '   hello "my name" is    "Tom"'.split(/\s+(?=(?:[^"]*"[^"]*")*[^"]*$)/)
Run Code Online (Sandbox Code Playgroud)

会为你工作.它会打印出来

=> ["", "hello", "\"my name\"", "is", "\"Tom\""]
Run Code Online (Sandbox Code Playgroud)

只需忽略空字符串.

说明

"
\\s            # Match a single character that is a “whitespace character” (spaces, tabs, and line breaks)
   +             # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
(?=           # Assert that the regex below can be matched, starting at this position (positive lookahead)
   (?:           # Match the regular expression below
      [^\"]          # Match any character that is NOT a “\"”
         *             # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
      \"             # Match the character “\"” literally
      [^\"]          # Match any character that is NOT a “\"”
         *             # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
      \"             # Match the character “\"” literally
   )*            # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
   [^\"]          # Match any character that is NOT a “\"”
      *             # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
   \$             # Assert position at the end of a line (at the end of the string or before a line break character)
)
"
Run Code Online (Sandbox Code Playgroud)

您可以reject像这样使用以避免空字符串

result = '   hello "my name" is    "Tom"'
            .split(/\s+(?=(?:[^"]*"[^"]*")*[^"]*$)/).reject {|s| s.empty?}
Run Code Online (Sandbox Code Playgroud)

版画

=> ["hello", "\"my name\"", "is", "\"Tom\""]
Run Code Online (Sandbox Code Playgroud)