正则表达式:是否可以仅对匹配模式的一部分使用"|"?



是否可以执行以下操作:

re.match(r'someArbLongRegex{option1|option2}anotherArbLongRegex', line)

与必须做的相反:

re.match(r'someArbLongRegexoption1anotherArbLongRegex|someArbLongRegexoption2anotherArbLongRegex', line)

基本上,|不应用于整个正则表达式模式,我只希望它应用于正则表达式模式的一小部分。

尝试使用(?:option1|option2(

re.match(r'someArbLongRegex(?:option1|option2)anotherArbLongRegex', line)

是。只需使用括号。

re.match(r'someArbLongRegex((option1)|(option2))anotherArbLongRegex', line)

有时,根据数据,您知道option1和option2不会都在"行"中,至少有一个会在"行中"中。然后你可以这样做:

re.match(r'(someArbLongRegex)((option1)?(option2)?)anotherArbLongRegex', line)

最新更新