我需要將字符串「/ [\ w \ s] + /」轉換爲正則表達式。將字符串轉換爲正則表達式ruby
"/[\w\s]+/" => /[\w\s]+/
我試圖使用像不同Regexp
方法:
Regexp.new("/[\w\s]+/") => /\/[w ]+\//
,類似地Regexp.compile
和Regexp.escape
。但他們沒有一個像我預期的那樣回報。
進一步我試圖消除反斜線:
Regexp.new("[\w\s]+") => /[w ]+/
但沒有運氣。
然後我試圖做到這一點很簡單:
str = "[\w\s]+"
=> "[w ]+"
它逃脫。現在字符串如何保持原樣並轉換爲正則表達式對象?
剛剛發現,你_can't_追加這樣的選項,比如'/#{your_regex} /#{options}'。 – pduersteler
我想你說的是Rails? 'options'是一個哈希,而Ruby不是那麼動態=) –
啊,是的。我試着通過它「ix」:) – pduersteler