Note: Many advance Regex functions are not available in several programming language as Python, Java 8, etc. Therefore, I included "in Python" that I'm using. A topic from regex101 about "Conditional statement" in the "Group Constructs" section: >>> re.search(r'(A candy)(?(1) is true| is false)', 'A candy is true') <re.Match object; span=(0, 15), match='A candy is true'> >>> re.search(r'(A candy)(?(1) is true| is false)', 'A candy is false') ( empty ) >>> re.search(r'(A candy)(?(1) is true| is false)', 'A candy is ok') ( empty ) And now I'm looking an expression to find the pattern i\d* or i([^()]+) but not enclosed in parentheses, for example >>> re.search(r'(?(1)|[^(])(i([^a-z)]+|\([^()]+\))?)(?(1)|[^)])', 'helloi123bye') <re.Match object; span=(4, 9), match='oi123'> >>> re.search(r'(?(1)|[^(])(i([^a-z)]+|\([^()]+\))?)(?(1)|[^)])', 'helloi(123b)ye') <re.Match object; span=(4, 12), match='oi(123b)'> >>> re.search(r'(?(1)|[^(])(i([^a-z)]+|\([^()]+\))?)(?(1)|[^)])', 'hello(i123)bye') ( empty ) >>> re.search(r'(?(1)|[^(])(i([^a-z)]+|\([^()]+\))?)(?(1)|[^)])', 'hello(ai123)bye') <re.Match object; span=(6, 11), match='ai123'> >>> re.search(r'(?(1)|[^(])(i([^a-z)]+|\([^()]+\))?)(?(1)|[^)])', 'i123hellobye') ( empty ) >>> re.search(r'(?(1)|[^(])(i([^a-z)]+|\([^()]+\))?)(?(1)|[^)])', 'hellobyei123') <re.Match object; span=(7, 12), match='ei123'> There are several results that I don't want: First, including a, o or e before the pattern i\d* or i([^()]+); Second, the pattern i\d* (including a before it) is enclosed in parentheses; Third, i\d* was not found in the entire string i123hellobye. Continue reading...