以下回答了标题和第三行中所要求的内容,这些内容是明确的。然而,这与预期的结果不一致。
r = /\A([^,]*,[^|]*)\|(.*)/x
"Little Miss Muffett, sat on | a tuffet".scan(r).first
#=> ["Little Miss Muffett, sat on ", " a tuffet"]
"Little | Miss, Muffett, sat on |, a | tuffet".scan(r).first
#=> ["Little | Miss, Muffett, sat on ", ", a | tuffet"]
我们可以在free-spacing模式中编写正则表达式以使其自文档化。
r = /
\A # match beginning of string
( # begin capture group 1
[^,]* # match 0 or more chars other than a comma
, # match a comma
[^|]* # match 0 or more chars other than a pipe
) # end capture group 1
\| # match a pipe
(.*) # match 0 or more chars and save to capture group 2
/x # invoke free-spacing regex definition mode
有关该方法如何处理包含捕获组的正则表达式的说明,请参阅 String#scan。1
不使用常规表达的第二种方法是使用String#index:
def split_it(str)
i = str.index(',')
return nil if i.nil?
j = str.index('|', i+1)
j.nil? ? nil : [str[0,j-1], str[j+1..-1]]
end
split_it("Little Miss Muffett, sat on | a tuffet")
#=> ["Little Miss Muffett, sat on", " a tuffet"]
split_it("Little | Miss, Muffett, sat on |, a | tuffet")
#=> ["Little | Miss, Muffett, sat on", ", a | tuffet"]
1 我将不加解释地给出一个替代方案,如下所示:“Little | Miss, Muffett, sat on |, a | tuffet”.match(/\A[^,], [^|]\K|/) && [$`, $'] #=> ["Little | Miss, Muffett, sat on ", ", a | tuffet"].