我有一个带有表的 Rails 应用程序:“clients”。客户表有一个字段:电话。电话数据类型是字符串。我正在使用 postgresql。我想编写一个查询,选择电话值包含超过 10 位数字的所有客户。电话没有特定格式:
+1 781-658-2687
+1 (207) 846-3332
2067891111
(345)222-777
123.234.3443
etc.
我一直在尝试以下变体:
Client.where("LENGTH(REGEXP_REPLACE(phone,'[^\d]', '')) > 10")
任何帮助都会很棒。
最佳答案
您几乎拥有它,但是您缺少 regexp_replace
的 'g'
选项,来自 fine manual :
The
regexp_replace
function provides substitution of new text for substrings that match POSIX regular expression patterns. [...] The flags parameter is an optional text string containing zero or more single-letter flags that change the function's behavior. Flagi
specifies case-insensitive matching, while flagg
specifies replacement of each matching substring rather than only the first one.
所以 regexp_replace(string, pattern, replacement)
表现得像 Ruby 的 String#sub
而 regexp_replace(string, pattern, replacement, 'g')
的行为类似于 Ruby 的 String#gsub
。
您还需要通过双引号 Ruby 字符串一直到 PostgreSQL 获取 \d
,因此您需要说 \\d
在你的 ruby 中。当每个人都想使用相同的转义字符时,事情往往会变得一团糟。
这应该做你想做的:
Client.where("LENGTH(REGEXP_REPLACE(phone, '[^\\d]', '', 'g')) > 10")
# --------------------------------------------^^---------^^^
关于ruby-on-rails - 按字段中的位数查询 Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33426432/