import re
regex = re.compile(r"(?:\bchapters?|c+)\s*((?:\s*([,&+]|and)?\s*(?:chapter|c)?\s*\d+(?:\.\d+)?(?:\s*-\s*(?:chapter|c)?\s*\d+)?)+)", flags=re.MULTILINE)
test_str = ("$title[] = 'c19 & c20'; \n"
"$title[] = 'text c19 & c20 text'; \n"
"$title[] = 'text chapter 19 and chapter 25 text'; \n"
"$title[] = 'text chapter 19 - chapter 23 and chapter 25 text'; \n"
"$title[] = 'text chapter 19 - chapter 23, chapter 25 text'; \n"
"$title[] = 'text chapter 23 text'; \n"
"$title[] = 'text chapter 23, chapter 25-29 text'; \n"
"$title[] = 'text chapters 23-26, 28, 29 + 30 + 32-39 text'; \n"
"$title[] = 'text chapter 25.6 text'; \n"
"$title[] = 'text chapters 23, 24, 25 text'; \n"
"$title[] = 'text chapters 23+24+25 text'; \n"
"$title[] = 'text chapter 23, 25 text'; \n"
"$title[] = 'text chapter 23 & 24 & 25 text'; \n"
"$title[] = 'text c25.5-30 text'; \n"
"$title[] = 'text c99-c102 text'; \n"
"$title[] = 'text chapter 1 - 3 text'; \n"
"$title[] = '33 text chapter 1, 2 text 3'; \n"
"$title[] = 'text v2c5-10 text'; \n"
"$title[] = 'text cccc5-10 text'; \n"
"$title[] = 'text chapters 23, 24, 25, 29, 31, 32 text'; \n")
matches = regex.finditer(test_str)
for match_num, match in enumerate(matches, start=1):
print(f"Match {match_num} was found at {match.start()}-{match.end()}: {match.group()}")
for group_num, group in enumerate(match.groups(), start=1):
print(f"Group {group_num} found at {match.start(group_num)}-{match.end(group_num)}: {group}")
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Python, please visit: https://docs.python.org/3/library/re.html