Home > Enterprise >  Regular expression to find text on previous lines but grab text on subsequent lines
Regular expression to find text on previous lines but grab text on subsequent lines

Time:08-31

How can I make my regex expression handle multilines in order to extract the text abc123xyz from the below string?

My regular expression: (\[customer\].*\n|..*\.*\n.*\[id\]\s*=>\s*)(.*)\n

Foo bar
(
    [customer] => Array
    (
        [id] => abc123xyz
        [accountNumber] => 1234
        [customerID] => 
    )

)

My current regex incorrectly grabs the text [customer] => Array.

An example here thats not quite working.

CodePudding user response:

You can enable the single-line option so that . matches newline characters too. You should also make the capturing pattern non-greedy to avoid capturing multiple lines:

\[customer\].*\n|..*\.*\n.*\[id\]\s*=>\s*(.*?)\n

Demo: https://regex101.com/r/MjmOfk/1

CodePudding user response:

You should take into account number of opened ( not a number of lines.

With PCRE

^[^(]*\([^(]*\[customer\][^(]*\([^(]*\[id\]\s =>\s*(\w )

This regex ignores newlines, so it's less brittle with varying numbers of newlines including zero newlines.

$1 will be abc123xyz

You can't use just \n - Match linebreaks - \n or \r\n?

  • Related