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

问题描述

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

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

Text:"How secure is my information?"

我需要提取文字 Text:

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 正则表达式中的后视.对于这样的表达式,您必须使用捕获括号:

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 正则表达式的正面回顾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 22:13