编辑:
你可以简单地使用
$regex
在查询中使用表达式
^ABC(?:.*?)\\d+$
MongoDB文档示例:
db={
"products": [
{
"name": "product A",
"product": "ABC-123"
},
{
"name": "product B",
"product": "ABC123"
},
{
"name": "product C",
"product": "ABC-123"
}
]
}
查询:
db.products.find({
"product": {
"$regex": "^ABC(?:.*?)\\d+$"
}
})
演示:
https://mongoplayground.net/p/WdqTg7LCZIk
我们也许能找到这个问题的表达式。或许,让我们从一个类似于以下的表达式开始:
product:\s+"(.+?)"
product:\s+"
作为左边的边界,我们收集任何字符,然后从右边将其与
"
.
const regex = /product:\s+"(.+?)"/gm;
const str = `{
name: "something"
product: "ABC-123"
}`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
或者我们可以将其扩展到我们喜欢捕获而不是捕获的内容:
(?:product:\s+")(.+?)(?:")