[Python] Why does Python regular expression give different result for the following 2...

Discussão em 'Python' iniciado por Stack, Fevereiro 18, 2025.

  1. Stack

    Stack Membro Participativo

    While investigating the semantic difference between quantifiers based on length and count, I noticed that Python 3 regular expression gave different result for the following 2 regular expressions (notice the quantifiers + and *:

    Python 3.10.16 (main, Dec 7 2024, 13:31:33) [Clang 16.0.0 (clang-1600.0.26.6)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import re
    >>> re.sub('(.{4,5})+', '-', '1234123412341234')
    '-4'
    >>> re.sub('(.{4,5})*', '-', '1234123412341234')
    '--4-'
    >>>


    And I was able to reproduce this in PHP, presumably because they both use PCRE behind the back:

    $ php -a
    Interactive shell

    php > echo preg_replace('/(.{4,5})+/', '-', '1234123412341234');
    -4
    php > echo preg_replace('/(.{4,5})*/', '-', '1234123412341234');
    --4-
    php >


    How come?

    Continue reading...

Compartilhe esta Página