Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Positive look behind in JavaScript regular expression

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:

How secure is my information? 

How do I do this with regex in Javascript

like image 647
Raj Avatar asked Aug 25 '10 18:08

Raj


People also ask

What is a positive lookahead regex?

The positive lookahead construct is a pair of parentheses, with the opening parenthesis followed by a question mark and an equals sign. You can use any regular expression inside the lookahead (but not lookbehind, as explained below). Any valid regular expression can be used inside the lookahead.

What is lookahead in regex JavaScript?

The syntax is: X(?= Y) , it means "look for X , but match only if followed by Y ". There may be any pattern instead of X and Y . For an integer number followed by € , the regexp will be \d+(?=

Does JavaScript regex support Lookbehind?

JavaScript doesn't support any lookbehind, but it can support lookaheads.

What is a negative Lookbehind?

A negative lookbehind assertion asserts true if the pattern inside the lookbehind is not matched.


1 Answers

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 (caniuse).

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:

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.

like image 73
Andy E Avatar answered Oct 02 '22 10:10

Andy E