vscode中正则表达式的不完整量词 [英] Incomplete Quantifier on Regex in vscode

查看:59
本文介绍了vscode中正则表达式的不完整量词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为对象的开头创建一个正则表达式,以便我可以在 vscode 的查找和替换中用单个 " 替换完整的块.

I am trying to create a regex expression for the beginning of an object so I can replace the block complete with a single " in vscode's find and replace.

我的正则表达式

("id":{"\$oid":)[0-9]+(},"product_id":)[0-9]+(,")

我的样本输入

{"id":{"$oid":973},"product_id":973,"product_name":"Scotch - Queen Anne","product_amount":92,"product_group":"not perishable","distribution_to":"The Salvation Army Visalia - Neighborhood Market","distribution_from":"MCFB","expiration_date":"8/24/2020","pack_date":"4/19/2021","sell_by_date":"12/6/2020","use_by_date":"2/18/2021","created_at":"2020-04-24 03:15:40 -0400","updated_at":"2020-04-24 03:15:40 -0400"},

我已经在这些网站上成功测试了这个表达式:regex101.com、regexr.com,但是,当我粘贴到我的 vscode 中时仍然出现错误.

I have tested this expression on these websites with success: regex101.com, regexr.com, however, I still get an error when I paste into my vscode.

推荐答案

这是一个有效的正则表达式,至少在 VS Code 使用的 JavaScript 引擎中(参见 这个答案),但我认为 VS Code 的验证引擎被未转义的花括号混淆了(就像我一样)——开头的 { 在第一组和第二组结束 }.

This is a valid regex, at least in the JavaScript engine used by VS Code (see this answer), but I think VS Code’s validation engine is confused (as was I) by the unescaped curly braces — the opening { being in the first group and the closing } in the second.

正如@rioV8 和@Nick 在评论中所建议的,您需要使用反斜杠 \ 将它们转义以使其工作:

As suggested by the @rioV8 and @Nick in the comments you’ll need to escape them with the back slash \ to make it work:

("id":\{"\$oid":)[0-9]+(\},"product_id":)[0-9]+(,")

<小时>

这是一个演示原始正则表达式在 JS 中工作的小演示:


Here’s a little demo that demonstrates that the original regex works in JS:

const regex = /("id":{"\$oid":)[0-9]+(},"product_id":)[0-9]+(,")/;

const sample = '{"id":{"$oid":973},"product_id":973,"product_name":"Scotch - Queen Anne","product_amount":92,"product_group":"not perishable","distribution_to":"The Salvation Army Visalia - Neighborhood Market","distribution_from":"MCFB","expiration_date":"8/24/2020","pack_date":"4/19/2021","sell_by_date":"12/6/2020","use_by_date":"2/18/2021","created_at":"2020-04-24 03:15:40 -0400","updated_at":"2020-04-24 03:15:40 -0400"},';

const result = sample.match(regex);

let output = [
  `full match:\t${result[0]}`,
  `group 1:\t${result[1]}`,
  `group 2:\t${result[2]}`,
  `group 3:\t${result[3]}`
]

document.querySelector("#result").innerText = output.join('\n');

<pre id=result></pre>

这篇关于vscode中正则表达式的不完整量词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆