JavaScript 正则表达式的正面回顾

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3569104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:14:40  来源:igfitidea点击:

Positive look behind in JavaScript regular expression

javascriptregex

提问by Raj

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

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

Text:"How secure is my information?"

I need to extract text which is in double quotes after the literal Text:

我需要提取文字后双引号中的文本 Text:

How secure is my information?

How do I do this with regex in Javascript

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

回答by Andy E

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.

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

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

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

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

较旧的浏览器不支持 JavaScript 正则表达式中的后视。您必须使用捕获括号来代替这样的表达式:

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.

然而,这不会涵盖所有的后视断言用例。

回答by Eddy

I just want to add something: JavaScript doesn'tsupport lookbehinds like (?<= )or (?<! ).

我只想补充一点:JavaScript支持像(?<= )(?<! ).

But it doessupport lookaheads like (?= )or (?! ).

但它确实支持像(?= )or那样的前瞻(?! )

回答by codaddict

You can just do:

你可以这样做:

/Text:"(.*?)"/

Explanation:

解释:

  • Text:": To be matched literally
  • .*?: To match anything in non-greedy way
  • (): To capture the match
  • ": To match a literal "
  • / /: delimiters
  • Text:": 字面上匹配
  • .*?: 以非贪婪的方式匹配任何东西
  • (): 捕捉比赛
  • ": 匹配文字 "
  • / /: 分隔符

回答by Sjoerd

<script type="text/javascript">
var str = 'Text:"How secure is my information?"';
var obj = eval('({'+str+'})')
console.log(obj.Text);
</script>

回答by Crayon Violent

string.match(/Text:"([^"]*)"/g)

回答by Bill Criswell

If you want to avoid the regular expression all together you can do:

如果你想避免使用正则表达式,你可以这样做:

var texts = file.split('Text:"').slice(1).map(function (text) {
  return text.slice(0, text.lastIndexOf('"')); 
});

回答by Piotr Berebecki

Here is an example showing how you can approach this.

这是一个示例,展示了如何处理此问题。

1) Given this input string:

1) 给定这个输入字符串:

const inputText = 
`Text:"How secure is my information?"someRandomTextHere
Voice:"Not very much"
Text:"How to improve this?"
Voice:"Don't use '123456' for your password"
Text:"OK just like in the "Hackers" movie."`;

2) Extract data in double quotes after the literal Text:so that the results is an array with all matches like so:

2) 在文字后提取双引号中的数据,Text:以便结果是一个包含所有匹配项的数组,如下所示:

["How secure is my information?",
 "How to improve this?",
 "OK just like in the \"Hackers\" movie."]

SOLUTION

解决方案

function getText(text) {
  return text
    .match(/Text:".*"/g)
    .map(item => item.match(/^Text:"(.*)"/)[1]);
}

console.log(JSON.stringify(    getText(inputText)    ));

RUN SNIPPET TO SEE A WORKING DEMO

运行片段以查看工作演示

const inputText = 
`Text:"How secure is my information?"someRandomTextHere
Voice:"Not very much"
Text:"How to improve this?"
Voice:"Don't use '123456' for your password"
Text:"OK just like in the "Hackers" movie."`;



function getText(text) {
  return text
    .match(/Text:".*"/g)
    .map(item => item.match(/^Text:"(.*)"/)[1]);
}

console.log(JSON.stringify(    getText(inputText)    ));