如何在Ruby字符類中說「除了反斜槓之外的所有符號」?正則表達式匹配除反斜線之外的任何字符
/'[^\]*'/.match("'some string \ hello'") => should be nil
變兩個反斜槓不起作用
/'[^\\]*'/.match("'some string \ hello'") => 'some string \ hello' BUT should be nil
如何在Ruby字符類中說「除了反斜槓之外的所有符號」?正則表達式匹配除反斜線之外的任何字符
/'[^\]*'/.match("'some string \ hello'") => should be nil
變兩個反斜槓不起作用
/'[^\\]*'/.match("'some string \ hello'") => 'some string \ hello' BUT should be nil
你的問題不在於你的正則表達式;你說對了。你的問題是你的測試字符串沒有反斜槓。它有一個逃脫的空間,相反。試試這個:
str = "'some string \\ hello'"
puts str #=> 'some string \ hello'
p /'[^\\]*'/.match(str) #=> nil
您需要轉義反斜線:
[^\\]*
因爲反斜線在正則表達式的轉義字符,從而逃避關閉括號在這裏。
如果您想驗證整個字符串包含非反斜槓字符,那麼你需要錨:
^[^\\]*$
我試了一下之前e寫這個問題,但它不起作用。 (紅寶石1.9.2) – 2012-07-24 20:39:09
那麼,它會匹配反斜槓 – Joey 2012-07-24 20:40:18
之前的部分*,它匹配整個字符串,我添加了單引號以顯示它 – 2012-07-24 20:46:08
實際上在你的字符串中沒有反斜槓來匹配。嘗試採取一看只是你輸入:
"'some string \ hello'".length # => 20
"a\ b".length # => 3
的「\」在雙引號被轉義成只是一個空間:
irb(main):014:0> " "[0].to_i # => 32
irb(main):015:0> "\ "[0].to_i # => 32
irb(main):016:0> "\ ".size #=> 1
如果你想匹配沒有斜線,你需要二,就像你的第二個例子,這對我來說很好:
/'[^\\]*'/.match("'some string \\ hello'") # => nil
Ruby的正則表達式調試一個很好的資源是:http://rubular.com/ – Teddy 2012-07-24 20:31:42
是的,尤其是當IRB不可 – 2012-07-24 20:55:03