【问题标题】:Mongo RegEx - Match all types of space charactersMongo RegEx - 匹配所有类型的空格字符
【发布时间】:2020-01-16 09:44:48
【问题描述】:

\s regex 通配符不匹配 mongodb (v4.0.3) 中所有类型的空间

> db.test.insertOne({ "mail" : "special email@example.com" })
> db.test.insertOne({ "mail" : "normal email@example.com" })

> db.test.find({ mail: / / }, { _id: 0, mail: 1 })
{ "mail" : "special email@example.com" }
> db.test.find({ mail: /\s/ }, { _id: 0, mail: 1 })
{ "mail" : "normal email@example.com" }

上面special email@example.com中的空间是特殊空间,normal email@example.com中的普通空间

这是预期的还是错误?有没有办法让它匹配所有的空格?

旁注:我在$not 中运行正则表达式,所以我不能使用$regex


编辑:即使[^\S] 也不匹配两个字符串

> db.test.find({ mail: /[^\S]/ }, { _id: 0, mail: 1 })
{ "mail" : "normal email@example.com" }

mongo 正则表达式是否仅适用于 ASCII?

【问题讨论】:

  • 您的“特殊”空间究竟是什么?比较\sMDN)的定义。
  • 好吧,JS 中的/\s/ 匹配两个字符串。 /\s/.test("special email@example.com") === /\s/.test("normal email@example.com")true
  • 两个字符串的btoa 看起来如何?
  • 对于带有The string to be encoded contains characters outside of the Latin1 range 的特殊电子邮件失败。普通邮件一封给bm9ybWFsIGVtYWlsQGV4YW1wbGUuY29t
  • btoa(unescape(encodeURIComponent("special email@example.com"))) === "c3BlY2lhbOKAhmVtYWlsQGV4YW1wbGUuY29t"escape("special email@example.com") 给出"special%u2006email@example.com"%u2006 而不是%20 空间

标签: regex mongodb


【解决方案1】:

Mongo 使用 PCRE 风格 https://docs.mongodb.com/manual/reference/operator/query/regex/#op._S_regex

https://www.pcre.org/original/doc/html/pcrepattern.html 读作:

现在默认的\s字符是HT(9)、LF(10)、VT(11)、FF(12)、CR(13)和空格(32),在" C”语言环境。如果进行特定于区域设置的匹配,此列表可能会有所不同。例如,在某些语言环境中,“不间断空格”字符 (\xA0) 被识别为空格,而在其他语言环境中,VT 字符不是。

您可以将\s 替换为

[\s\x00a0\x1680\x2000\x2001\x2002\x2003\x2004\x2005\x2006
\x2007\x2008\x2009\x200a\x2028\x2029\x202f\x205f\x3000\xfeff]

(为了可读性而拆分)与 ECMA 正则表达式风格兼容。

您可能需要将代码包装到 {} 中,具体取决于 shell/客户端,例如\x{00a0}\x{1680} 等等。

对于您的查询,它将是:

db.test.find({ mail: /[\s\x{00a0}\x{1680}\x{2000}\x{2001}\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}\x{200a}\x{2028}\x{2029}\x{202f}\x{205f}\x{3000}\x{feff}]/ }, { _id: 0, mail: 1 })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-01
    • 1970-01-01
    相关资源
    最近更新 更多