简体   繁体   English

在正则表达式中重复大元素

[英]Repeating large elements in a regular expression

I have the following regular expression: 我有以下正则表达式:

_parser = re.compile('''
                    (?P<a>-?[0-9]+(\.[0-9]+)?(/-?[0-9]+(\.[0-9]+)?)?)?x[+\-]
                    (?P<b>-?[0-9]+(\.[0-9]+)?(/-?[0-9]+(\.[0-9]+)?)?)?y[+\-]
                    (?P<c>-?[0-9]+(\.[0-9]+)?(/-?[0-9]+(\.[0-9]+)?)?)?=0
                    ''', re.VERBOSE)

This quite obviously has a lot of repetition in it, so it got me wondering, what's the syntax (if it exists) to repeat blocks of similar expressions in a single expression? 这显然有很多重复,所以让我想知道,在单个表达式中重复相似表达式的块的语法(如果存在)是什么?

You can do this: 你可以这样做:

Surround [0-9]+(\\.[0-9]+)?(/-?[0-9]+(\\.[0-9]+) in another capture group, and then refer to it with \\2 , since it's the second open-paren in the regex: [0-9]+(\\.[0-9]+)?(/-?[0-9]+(\\.[0-9]+)包围在另一个捕获组中,然后用\\2引用\\2 ,因为它是正则表达式中的第二个开放式括号:

_parser = re.compile('''
     (?P<a>-?([0-9]+(\.[0-9]+)?(/-?[0-9]+(\.[0-9]+))?)?)?x[+\-]
              (?P<b>-?\2?)?)?y[+\-]
                (?P<c>-?\2?)?)?=0
                ''', re.VERBOSE)

You could also do this by creating the string of the regex, and then using that string-variable repeatedly. 您还可以通过创建正则表达式的字符串,然后重复使用该字符串变量来执行此操作。 I don't know Python, but in Java it'd be something like this: 我不了解Python,但是在Java中会是这样:

String sRegexPiece = "[0-9]+(\\.[0-9]+)?(/-?[0-9]+(\\.[0-9]+)";
String sRegexWhole = "(?P<a>-?" + sRegexPiece + "?)?x[+\-]" + sLS + //sLS: line separator
    "(?P<b>-?" + sRegexPiece + "?)?)?y[+\-]" + sLS + 
    "(?P<c>-?" + sRegexPiece + "?)?)?=0" + sLS + 
    "'''";
Pattern p = Pattern.compile(sRegexWhole);

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

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