Search code examples
phpregexpreg-match-allcapturing-group

How to not include in regex a literal after including it in the first group?


I am using preg_match_all() to match some strings.

this is my code

preg_match_all('@([a-zA-Z0-9,\(\)\-\s\.\#:]*)Date From: [0-9]{2}/[0-9]{2}/[0-9]{4}([, \s]*[0-9]{2}/[0-9]{2}/[0-9]{4})*\s(Division Type: [A-Z ]*)*@m', $string, $match);

this is the output

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

Now, I want to add a / to the first group to include the literal / in the capturing group and this happen

from this

([a-zA-Z0-9,\(\)\-\s\.\#:]*)

to this

([a-zA-Z0-9,\(\)\-\s\.\#:/]*)

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

How can I prevent this to happen when adding / to the group?


Solution

  • Make your regex non-greedy:

    ([a-zA-Z0-9,()\s.#:/-]*?)Date From: [0-9]{2}/[0-9]{2}/[0-9]{4}([, \s]*[0-9]{2}/[0-9]{2}/[0-9]{4})*\s(Division Type: [A-Z ]*)*
    

    RegEx Demo