我正在尝试按照Mongo DB specification为Mongo DB集合名称添加路由时间(在REST API建模期间)正则表达式验证(蒙戈3.6)。
它说(从上面的文档复制粘贴):
Restriction on Collection Names
Collection names should begin with
- an underscore or a letter character
and cannot:
- contain the $.
- be an empty string (e.g. "").
- contain the null character.
- begin with the system. prefix. (Reserved for internal use.)
我的另一个限制(某种程度上)是:它用于 JSON 模式验证,按照 json-schema supported subset of the regexp 。它不是完整的正则表达式(例如我不能使用\d、\w (或者我不能使用\b<...>\b)。
有了这个,到目前为止,我可以在没有的情况下完成其他部分
- begin with the system. prefix. (Reserved for internal use.)
部分。
这是我的 REST API JSON 架构中的正则表达式(请参阅下面的模式):
'collectionName': {
description: "foo bar",
type: 'string',
minLength: 1,
maxLength: 120,
pattern: '(^[a-zA-Z0-9_][^$ \\0]*$)', <== this one.
example: 'MyCollection',
},
用几个例子进一步说明:
- 它不应匹配类似 -collection 的内容,但应匹配 _collection 或 collection-tion
- 字符串包含空格或 $ - 不应匹配(例如,collection、collection$$tion)
- 类似这样的内容应该匹配:systemCollection
- 此不应匹配:system.collection//as system。前缀是为 Mongo 保留的。
尽我所能以最好的方式澄清问题。
在这方面的任何帮助将不胜感激。
普拉迪普
最佳答案
您需要负面的前瞻。
^(?!system\.)[a-zA-Z0-9_][^$\\0]*$
(?!...)
Starting at the current position in the expression, ensures that the given pattern will not match. Does not consume characters. - regex101.com
这与 PCRE 中的 ECMAScript 相同。 MongoDB 使用 PCRE 作为其正则表达式,因此我认为 MongoDB 的 JSON 模式中的正则表达式也是如此。
这是一个使用示例数据测试用例的示例 https://regex101.com/r/CHu6lz/1
我只介绍了您所说的不以system.
开头的情况。您需要扩展正则表达式来添加额外的情况,但现在您已经了解了负向先行,应该清楚如何做到这一点。
您还需要转义正则表达式以在 JSON 中使用,根据此答案的评论以及您已经完成的操作。
关于用于匹配不能包含某些字符或子字符串的字符串的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68479646/