Robert Calove
Robert Calove

Reputation: 449

How to capture text between single quotes after a positive lookbehind?

I am trying to parse an error string in order to return meaningful output in an API. Here is a sample of the error string:

Integrity constraint violation: 1062 Duplicate entry '[email protected]' for key 'UNIQ_8D93D649A0D96FBF'

I am attempting to parse [email protected] out of this sentence. This is my current regex:

/(?<=Duplicate entry ')(.*)'/

I'm doing a positive look behind for Duplicate entry ' which gets me to the beginning of the string that I want. Then I want to capture everything until I reach a single quote. However, this regex is capturing the following:

[email protected]' for key 'UNIQ_8D93D649A0D96FBF'

So my regex is capturing all the way to the final end single quote. My initial hunch is that I need to do a positive lookahead that's not-greedy.

Upvotes: 1

Views: 243

Answers (1)

ctwheels
ctwheels

Reputation: 22837

Brief

The issue you're experiencing is because quantifiers are greedy by default. Changing .* to .*? will fix your issue, but using [^']* is considered more correct (and also performs better) since it doesn't backtrack.


Results

Input

Integrity constraint violation: 1062 Duplicate entry '[email protected]' for key 'UNIQ_8D93D649A0D96FBF'

Output

[email protected]

Code

See regex in use here

(?<=Duplicate entry ')[^']*

Upvotes: 1

Related Questions