JavaScript正则表达式背后的正面看法 [英] Positive look behind in JavaScript regular expression

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

问题描述

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

I've a document from which I need to extract some data. Document contain strings like these

Text:"How secure is my information?"

我需要在文字文本之后提取双引号的文本:

How secure is my information?

如何在Javascript中使用正则表达式执行此操作

How do I do this with regex in Javascript

推荐答案

Lookbehind断言最近已针对JavaScript进行了最终确定,并将出现在ECMA-262规范的下一个出版物中。 Chrome 66(Opera 53)支持它们,但在撰写本文时没有其他主流浏览器。

Lookbehind assertions were recently finalised for JavaScript and will be in the next publication of the ECMA-262 specification. They are supported in Chrome 66 (Opera 53), but no other major browsers at the time of writing.

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

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

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

Older browsers do not support lookbehind in JavaScript regular expression. You have to use capturing parenthesis for expressions like this one instead:

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

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

然而,这并不包括所有看起来断言的用例。

This will not cover all the lookbehind assertion use cases, however.

这篇关于JavaScript正则表达式背后的正面看法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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