我經常看到正在調用的gsub函數,其模式參數以正斜槓包圍。例如:在Ruby中使用GSUB和正斜槓使用
>> phrase = "*** and *** ran to the @@@."
>> phrase.gsub(/\*\*\*/, "WOOF")
=> "WOOF and WOOF ran to the @@@."
我想也許這已經是與逃逸星號,但使用單引號和雙引號的作品一樣好:
>> phrase = "*** and *** ran to the @@@."
>> phrase.gsub('***', "WOOF")
=> "WOOF and WOOF ran to the @@@."
>> phrase.gsub("***", "WOOF")
=> "WOOF and WOOF ran to the @@@."
難道只是約定使用斜線?我錯過了什麼?
如果你不想做轉義工作,你可以用'Regexp.escape(「***」)來幫助你自己(結果是'\ * \ * \ *'') – knut