Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Perl equivalent of PCRE's PCRE_PARTIAL?

Tags:

c

regex

perl

pcre

Is there a way for a Perl regular expression to do a partial match, i.e. some variation of the following expression should return true.

perl -le 'print "aa" =~ /aaaa/'

Here is the equivalent PCRE code that does this.

$ cat partial.c 
#include <stdio.h>
#include <pcre.h>

int main(void)
{
    const char *errptr;
    int erroffset, result;
    pcre *re;

    re = pcre_compile("aaaa", 0, &errptr, &erroffset, NULL);
    if (re == NULL)
        return 42;

    result = pcre_exec(re, NULL, "aa", 2, 0, PCRE_PARTIAL, NULL, 0);

    printf("%d\n", result == PCRE_ERROR_PARTIAL);

    return 0;
}

$ make partial LDFLAGS=-lpcre
cc   -lpcre  partial.c   -o partial

$ ./partial 
1

EDIT: The pcretest tool can be used to demonstrate the difference between partial and non-partial matches. Also include result of matching the regex suggested by @revo in comments.

$ pcretest
PCRE version 8.41 2017-07-05

  re> /aaaa/

data> aa
No match

data> aa\P
Partial match: aa
data> aaaa
 0: aaaa

$ pcretest
PCRE version 8.41 2017-07-05

  re> /aaa?a?/

data> aa
 0: aa

data> aa\P
 0: aa
like image 736
sigjuice Avatar asked Feb 09 '18 10:02

sigjuice


1 Answers

There is no simple way to do this with Perl regexes. Perl's match operator either returns true (match found) or false (match not found).

There are possible workarounds if you know what pattern you're dealing with (by rewriting the pattern to do partial matching manually), but there's no general solution as far as I'm aware.

like image 66
melpomene Avatar answered Sep 28 '22 16:09

melpomene