Why does the end repetition in lookbehind not work in some cases?

I want to analyze 2 digits in the middle of the date in a format dd/mm/yy, but also allow single digits for the day and month.

Here is what I came up with:

(?<=^[\d]{1,2}\/)[\d]{1,2}

I want a 1 or 2 digit number [\d]{1,2}with a 1 or 2 digit number and a slash ^[\d]{1,2}\/before it.

This does not work for many combinations, I tested 10/10/10, 11/12/13etc.

But to my surprise, it (?<=^\d\d\/)[\d]{1,2}worked.

But [\d]{1,2}should it also coincide if I \d\ddid, or am I mistaken?

+3
source share
4 answers

With lookbehind support

lookbehind -; , .

  • Javascript:
  • Python:
  • Java:
  • .NET:


Python

Python, lookbehind, , \d{1,2}, , . "" , , . - :

(?<=^\d\/)\d{1,2}|(?<=^\d\d\/)\d{1,2}

, , lookbehind :

(?:(?<=^\d\/)|(?<=^\d\d\/))\d{1,2}

( , \d ).

, , :

^\d{1,2}\/(\d{1,2})

, findall , 1 , . , lookbehind, (, ).

:

p = re.compile(r'(?:(?<=^\d\/)|(?<=^\d\d\/))\d{1,2}')

print(p.findall("12/34/56"))   # "[34]"
print(p.findall("1/23/45"))    # "[23]"

p = re.compile(r'^\d{1,2}\/(\d{1,2})')

print(p.findall("12/34/56"))   # "[34]"
print(p.findall("1/23/45"))    # "[23]"

p = re.compile(r'(?<=^\d{1,2}\/)\d{1,2}')
# raise error("look-behind requires fixed-width pattern")


Java

Java lookbehind, \d{1,2} . :

    String text =
        "12/34/56 date\n" +
        "1/23/45 another date\n";

    Pattern p = Pattern.compile("(?m)(?<=^\\d{1,2}/)\\d{1,2}");
    Matcher m = p.matcher(text);
    while (m.find()) {
        System.out.println(m.group());
    } // "34", "23"

, (?m) Pattern.MULTILINE, ^ . , \ escape- , "\\", Java.


C-Sharp

# lookbehind. , + lookbehind:

var text = @"
1/23/45
12/34/56
123/45/67
1234/56/78
";

Regex r = new Regex(@"(?m)(?<=^\d+/)\d{1,2}");
foreach (Match m in r.Matches(text)) {
  Console.WriteLine(m);
} // "23", "34", "45", "56"

, Java, # @- , \.

#:

Regex r = new Regex(@"(?m)^\d+/(\d{1,2})");
foreach (Match m in r.Matches(text)) {
  Console.WriteLine("Matched [" + m + "]; month = " + m.Groups[1]);
}

text, :

Matched [1/23]; month = 23
Matched [12/34]; month = 34
Matched [123/45]; month = 45
Matched [1234/56]; month = 56

+13

lookbehind, , , ?

JavaScript:

>>> /^\d{1,2}\/(\d{1,2})\/\d{1,2}$/.exec("12/12/12")[1]
"12"
+4

regular-expressions.info:

, lookbehind, . , lookbehind.

, Perl Python, . . , . . , .

, , lookbehind, regex .

+3

, @polygenelubricants, " ". PCRE ( PHP, Apache .) Oniguruma (Ruby 1.9, Textmate), lookbehind , , . :

(?<=\b\d\d/|\b\d/)\d{1,2}(?=/\d{2}\b)

, lookbehind. , , , :

(?<=\b(?:\d\d/|\d)/)\d{1,2}(?=/\d{2}\b)

... ; .

: \K, Perl PCRE. ", ". , , lookbehind. .NET lookbehinds, ; , , \K.

\b\d{1,2}/\K\d{1,2}(?=/\d{2}\b)

, - lookbehinds, , . @insin, .

EDIT: Almost forgot JGSoft, the regex flavor used by EditPad Pro and PowerGrep; like .NET, it has completely unlimited lookbehinds, positive and negative.

+2
source

Source: https://habr.com/ru/post/1752670/


All Articles