I have an Regex with multiple optional and Non-Capturing Groups. All of these groups can occur, but don't have to. The Regex should use Non-Capturing Groups to return the whole string.
When I set the last group also as optional, the Regex will have several grouped results. When I set the first group as not-optional, the Regex matches. Why is that?
The input will be something like input_text = "xyz T1 VX N1 ", expected output T1 VX N1.
regexs = {
"allOptional": 'p?(?:T[X0-4]?)?\\s?(?:V[X0-2])?\\s?(?:N[X0-3])?',
"lastNotOptional": 'p?(?:T[X0-4]?)?\\s?(?:V[X0-2])?\\s?(?:N[X0-3])',
"firstNotOptional": 'p?(?:T[X0-4]?)\\s?(?:V[X0-2])?\\s?(?:N[X0-3])?',
}
for key, regex in regexs.items():
matches = re.findall(regex, input_text)
# Results
allOptional = ['', '', '', ' ', 'T1 VX N1', '']
lastNotOptional = ['T1 VX N1']
firstNotOptional = ['T1 VX N1']
Thanks in advance!