我將正則運算式存盤在變數 - 中
s="/\A([^@\s] )@((?:a-b \.) (in|com))\z/"。
"[email protected]".match?(/\A([^@\s] )@((?:a-b \.) (in|com))\z/) => returns true
Regexp.new(s) => returns /\/A([^@ ] )@((?:a-b .) (in|com))z\//
"sourabh@a-b.in".match?(Regexp.new(s)) => returns false
將正則運算式存盤在資料庫中時\會自動洗掉。我將以字串的形式獲取正則運算式驗證器。不知道為什么它不起作用?
uj5u.com熱心網友回復:
使用單引號代替雙引號(參見本頁)
> puts "/\A([^@\s] )@((?:a-b \.) (in|com))\z/"
/A([^@ ] )@((?:a-b .) (in|com))z/
> puts '/\A([^@\s] )@((?:a-b \.) (in|com))\z/'
/\A([^@\s] )@((?:a-b \.) (in|com))\z/
然后洗掉開頭和結尾的“/”:
> s = '\A([^@\s] )@((?:a-b \.) (in|com))\z'
=> "\\A([^@\\s] )@((?:a-b \\.) (in|com))\\z"
> reg = Regexp.new s
=> /\A([^@\s] )@((?:a-b \.) (in|com))\z/
> "sourabh@a-b.in".match?(Regexp.new(reg))
=> true
uj5u.com熱心網友回復:
當您需要在資料庫中存盤正則運算式模式時,一種常見的方法是將模式/標志存盤為字串。
因此,如果您打算使用單列來存盤正則運算式資料,您可以使用Regexp#to_s:
regex_string = /.../.to_s
如果要將模式 ( source) 和標志 ( options) 存盤為單獨的字串:
regex_pattern = /\A([^@\s] )@((?:a-b \.) (in|com))\z/.source
regex_flags = /\A([^@\s] )@((?:a-b \.) (in|com))\z/.options
從資料庫中讀取值后,您可以使用Regexp.new建構式獲取正則運算式物件:
rx = Regexp.new(regex_string)
# or
rx = Regexp.new(regex_pattern, regex_flags)
請參閱RegexpRuby 檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/374144.html
下一篇:字串回文
