gpt4 book ai didi

javascript - JavaScript 正则表达式中的正面观察

转载 作者:IT王子 更新时间:2023-10-29 03:19:43 25 4
gpt4 key购买 nike

我有一份文档,需要从中提取一些数据。文档包含这样的字符串

Text:"How secure is my information?"

我需要在文字 Text:

之后提取双引号中的文本
How secure is my information?

我如何在 Javascript 中使用正则表达式来做到这一点

最佳答案

Lookbehind 断言最近针对 JavaScript 最终确定,并将出现在 ECMA-262 规范的下一次发布中。它们在 Chrome 66 (Opera 53) 中受支持,但在撰写本文时不支持其他主要浏览器 (caniuse)。

var str = 'Text:"How secure is my information?"',
reg = /(?<=Text:")[^"]+(?=")/;

str.match(reg)[0];
// -> How secure is my information?

旧版浏览器不支持 JavaScript 正则表达式中的 lookbehind。您必须为这样的表达式使用捕获括号:

var str = 'Text:"How secure is my information?"',
reg = /Text:"([^"]+)"/;

str.match(reg)[1];
// -> How secure is my information?

但是,这不会涵盖所有后向断言用例。

关于javascript - JavaScript 正则表达式中的正面观察,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3569104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com