# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"([^\|\s]\s*\[x\]\s*\K[^!|\n]*|(?:\G(?!\A)\||(?<=\[x]\s)\s*\|)\K[^|\n]*(?=\|))|([^\|\s]\s*\[x\]\s*\!\s*\K[^|\n]*|(?:\G(?!\A)\||(?<=\[x]\s)\s*\!\s*\|)\K[^|\n]*(?=\|))"
test_str = ("Text for testing:\n"
"- [x] Example task. | Task ends. [x] Another task.\n"
"- [x] ! Example task. | This ends. [x] ! Another task.\n\n"
"This is a sentence. [x] Task is here.\n"
"Other text. Another [x] ! Task is here.\n\n"
"| | Task name | Plan | Actual | File |\n"
"| :---- | :-------------| :---------: | :---------: | :------------: |\n"
"| [x] | Task example. | 08:00-08:45 | 08:00-09:00 | [[task-one]] |\n"
"| [x] ! | Task example. | 08:00-08:45 | 08:00-09:00 | [[task-one]] |\n\n"
"Description:\n"
"- $1:\n"
" - outside the table: capture everything after `[x]` (i.e., not followed by `!`) until a `|`\n"
" - inside the table: capture everything after `[x]` (i.e., not followed by `!`) excluding the `|` symbols\n"
"- $2:\n"
" - outside the table: capture everything after `[x] !` until a `|`\n"
" - inside the table: capture everything after `[x] !` excluding the `|` symbols\n\n"
"Expressions for each group:\n"
"- $1:\n"
" - outside the table: [^\\|\\s]\\s*\\[x\\]\\s*\\K[^!|\\n]*\n"
" - inside the table: (?:\\G(?!\\A)\\||(?<=\\[x]\\s)\\s*\\|)\\K[^|\\n]*(?=\\|)\n"
"- $2:\n"
" - outside the table: [^\\|\\s]\\s*\\[x\\]\\s*\\!\\s*\\K[^|\\n]*\n"
" - inside the table: (?:\\G(?!\\A)\\||(?<=\\[x]\\s)\\s*\\!\\s*\\|)\\K[^|\\n]*(?=\\|)\n\n"
"Combined expression:\n"
"([^\\|\\s]\\s*\\[x\\]\\s*\\K[^!|\\n]*|(?:\\G(?!\\A)\\||(?<=\\[x]\\s)\\s*\\|)\\K[^|\\n]*(?=\\|))|([^\\|\\s]\\s*\\[x\\]\\s*\\!\\s*\\K[^|\\n]*|(?:\\G(?!\\A)\\||(?<=\\[x]\\s)\\s*\\!\\s*\\|)\\K[^|\\n]*(?=\\|))\n")
matches = re.finditer(regex, test_str, re.MULTILINE)
for matchNum, match in enumerate(matches, start=1):
print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
for groupNum in range(0, len(match.groups())):
groupNum = groupNum + 1
print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
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