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
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.
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+(?=
JavaScript doesn't support any lookbehind, but it can support lookaheads.
A negative lookbehind assertion asserts true if the pattern inside the lookbehind is not matched.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With