-1

I needed a regex to find an exact number of matching digits in a string of digits. (example, "exactly three repeating-digits")

On regex101 I got a functioning regular expression (^|(.)(?!\2))(\d)\3{2}(?!\3)

but when I try it in a python3.6 shell, it fails, with match returning None:

import re
three_char_re  = re.compile("(^|(.)(?!\2))(\d)\3{2}(?!\3)")
print(three_char_re.match("14551114"))

Is there some default flag that differs between my python environment and regex101 perhaps? I cannot find a difference in the regex or the test input.

3
  • So the pattern itself is correct? Commented Dec 4, 2019 at 5:58
  • 1
    @Thefourthbird i dont think so...but m not sure what OP is looking for Commented Dec 4, 2019 at 6:00
  • yes, the expression is correct. Commented Dec 4, 2019 at 7:44

3 Answers 3

3

There are two problems here:

Use raw strings (see https://docs.python.org/3/reference/lexical_analysis.html) for Python regexps. Hint: ”\d” is not a backslash followed by a “d”. Change it like:

three_char_re  = re.compile(r"(^|(.)(?!\2))(\d)\3{2}(?!\3)")

Notice that it’s compile(r”...”), not compile(“...”)? The short version is that this preserves the backslashes.

Second, Use three_char_re.search or three_char_re.find_all instead of .match, so that you can find matches that aren’t at the start of the input string.

Sign up to request clarification or add additional context in comments.

Comments

0
import re
three_char_re  = re.compile(r"(^|(.)(?!\2))(\d)\3{2}(?!\3)")
print(three_char_re.findall("14551114"))

Output: [('5', '5', '1')]

You need to use findall as match starts from first character and your regex does not match from first character.

1 Comment

also my expression didn't have the leading 'r' (eg. re.compile(r"(^|(.".
0

You need to declare your pattern as a raw string to escape \ character with prefix r.

This following pattern will search for the 3 first successive identical digits

import re
result = re.search(r"([0-9])\1\1","14551114")) 
# <re.Match object; span=(4, 7), match='111'>
print(result.group() 
# '111'

1 Comment

yeah, the complexity is that it there must be a case of exactly 3 digits, no more no less. 1222456 True, 1222245 False, 13335660 True, 1333349990 True

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.