Search code examples
regexpcre

Regex AND search inside block which enclosed by something delimiter


I want to regex AND search (?=)(?=) inside block which enclosed by something delimiter such as #

In following sample regex, what I expected is, cat to ugly matches to the pattern inside # cat B to before # cat C.
But the regex match to nothing.

regex

^#(?=[\s\S]*(cat))(?=[\s\S]*(ugly))^#

text


# cat A

the cat is
very cute.

# cat B

the cat is
very ugly.

# cat C

the cat is
very good.

#

You can test the regex on https://regexr.com/


Solution

  • In your pattern ^#(?=[\s\S]*(cat))(?=[\s\S]*(ugly))^# you use match a # from the start of the string ^#, followed by 2 positive lookaheads and then again match ^#. That is why you don't get a match.

    To get a more exact match, you could start the pattern with ^# cat B

    If you want to use lookaheads, you might use 2 capturing groups in the positive lookahead. If you want to search for cat and ugly as whole words you might use word boundaries \b.

    The (?s) is a modifier that enables the dot matching a newline for which you might also use /s as a flag instead.

    (?s)(?=^# cat B.*?(cat).*?(ugly).*?^# cat C
    

    Regex demo

    But it might be easier to not use the lookahead and match instead:

    (?s)^# cat B.*?(cat).*?(ugly).*?^# cat C$
    

    Php demo