Search code examples
regexregex-group

Regex Match if present does not match a line


I have a set of strings coming in as:

  • Site: 4442.001 Rental Charge (x 1) PU094928
  • Exchange1 x 6m Marrell - Construction &
  • Emptying of bin1 x 240L - Commercial & PU094928

I want to match it into 3 columns if Site*** presents at the start and if P*** presents in the end else match all of it

I am trying

^(.*)??(Site\S\s\d+\S\d+)?(.*)?\s(P.*?)$

But it is missing

  • Exchange1 x 6m Marrell - Construction &

How can I do it?

Regex: PCRE(PHP<7.3)


Solution

  • the last part, including \s needs to be optional to match the string without it

    try

    ^(Site\S\s\d+\S\d+)?(.*?)((\s)P.*)?$
    

    https://regex101.com/r/SuvUDb/1