简体   繁体   English

适用于Python的嵌套正则表达式

[英]Nested Regular Expression in Python for

Is there a way to do nested regular expression in Python? 有没有办法在Python中做嵌套的正则表达式? For example I have 例如我有

r1 = re.compile(r'SO ON')

can I have something like 我可以有类似的东西吗

r2 = re.compile(r'WHATEVER AND (r1)*') 

to validate "WHATEVER AND SO ON" for this example. 验证此示例的“无论如何”。

I tried finding about this around but couldn't find any solution. 我试图找到有关此问题,但找不到任何解决方案。

r1 = re.compile(r'SO ON')
r2 = re.compile(r'WHATEVER AND (%s)*' % r1.pattern)

This isn't actually using any special feature of regex, it's using string formatting . 这实际上并没有使用正则表达式的任何特殊功能,而是使用字符串格式 Multiple strings can be passed in as: 可以按以下方式传递多个字符串:

r'WHATEVER AND (%s) (%s)' % (r1.pattern, 'hello')

I feel a moral obligation to point out that this is strictly supportive of regexen with no flags. 我感到有道德义务要指出,这严格支持regexen,没有任何标志。 As soon as you start using flags like re.MULTILINE this approach does not work. 一旦您开始使用诸如re.MULTILINE之类的标志,此方法将不起作用。 Perl was great with regex inside regex. Perl在regex中使用regex很棒。 I wish I could find a good Python solution. 我希望我能找到一个好的Python解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM