簡體   English   中英

拆分正則表達式並將結果放入數組時遇到問題

[英]Having trouble splitting on a regular expression and putting the results into an array

我正在使用 Ruby 2.4。 我在拆分正則表達式並將結果放入數組時遇到問題。 如果我有一個像

"A other stuff"

我想從字符串的其余部分拆分第一個字符,僅當第一個字符是“A”或“B”並且后面有一個空格時。 因此,根據這些規則,拆分上述內容將導致

["A", "other stuff"]

但將這些規則應用於

"Aother stuff"

會導致

["Aother stuff"]

(因為“A”后沒有空格)。 我試過

2.4.0 :007 > str = "A more"
 => "A more" 
2.4.0 :009 > str.split(/^([ab])[[:space:]]+/i)
 => ["", "A", "more"]

但是在我的數組開頭有這個煩人的空白字符,我不想要那里。 感謝您的建議。

使用后視斷言(這意味着前面有):

yourstring.split(/(?<=^[ab])\s+/i)

環視斷言的主要興趣在於它們只是測試,它們不消耗字符並且不會在匹配結果中返回。

注意,由於你只需要拆分一次你的字符串,可能如果你將split方法的第二個參數設置為2,它會在第一次出現時停止搜索(需要確認):

 yourstring.split(/(?<=^[ab])\s+/i, 2)

這是一種不使用正則表達式的方法。

def doit(str)
  (!str.empty? && "ABab".include?(str[0]) && str[1] == ' ') ?
    [str[0], str[2..-1].lstrip] : [str]
end

doit 'A lot of stuff'     #=> ["A", "lot of stuff"] 
doit 'B     lot of stuff' #=> ["B", "lot of stuff"] 
doit 'C lot of stuff'     #=> ["C lot of stuff"] 
doit 'Alot of stuff'      #=> ["Alot of stuff"] 
doit 'B '                 #=> ["B", ""] 
doit 'b'                  #=> ["b"] 
doit ''                   #=> [""] 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM