user837208
user837208

Reputation: 2577

Extract last value from key value pair using regex

Here is sample text-

display_errors = On
display_errors= Off
display_errors = On

I would like to extract the value of last display_errors. How do I do that?

So far, I've display_errors =(?!.*display_errors = ) which is able to match display_errors = but I want its value, not the key.

I am using libpcre for matching with . matches all option

Please note I've to use regex and not any .ini parsing library.

Upvotes: 0

Views: 159

Answers (2)

newfurniturey
newfurniturey

Reputation: 38416

Try the following:

display_errors\s*=\s*([a-zA-Z]+)(?!.*display_errors\s*=)

That should match the last value for the display_errors key, assuming the values are characters a-z (but the accepting-character list can easily be updated if needed).

Upvotes: 1

TimD
TimD

Reputation: 1381

Split the text by newlines, loop over each line with a regexp like this:

display_errors ?= ?(On|Off)

Compile that with case-insensitivity to catch slight errors. Capture the value of the first group to get the status from that match. In each iteration of the loop, just overwrite a variable with the current status in, after the loop has ended, the variable will contain the value for the last display_errors.

Upvotes: 0

Related Questions