如何在Python中调试正则表达式?

Geo*_*Geo 16 python regex debugging

有没有办法在Python中调试正则表达式?而且我不是指尝试和尝试直到他们工作的过程:)

以下是如何在Perl中调试正则表达式:


use re 'debug';

my $str = "GET http://some-site.com HTTP/1.1";
if($str =~/get\s+(\S+)/i) {
    print "MATCH:$1\n";
}
Run Code Online (Sandbox Code Playgroud)

上面的代码在运行时在我的计算机上产生以下输出:


Compiling REx "get\s+(\S+)"
Final program:
   1: EXACTF  (3)
   3: PLUS (5)
   4:   SPACE (0)
   5: OPEN1 (7)
   7:   PLUS (9)
   8:     NSPACE (0)
   9: CLOSE1 (11)
  11: END (0)
stclass EXACTF  minlen 5
Matching REx "get\s+(\S+)" against "GET http://some-site.com HTTP/1.1"
Matching stclass EXACTF  against "GET http://some-site.com HTTP/1.1" (33 chars)
   0           |  1:EXACTF (3)
   3        |  3:PLUS(5)
                                  SPACE can match 1 times out of 2147483647...
   4       |  5:  OPEN1(7)
   4       |  7:  PLUS(9)
                                    NSPACE can match 20 times out of 2147483647...
  24       |  9:    CLOSE1(11)
  24       | 11:    END(0)
Match successful!
MATCH:http://some-site.com
Freeing REx: "get\s+(\S+)"

Run Code Online (Sandbox Code Playgroud)

Myk*_*hko 17


>>> p = re.compile('.*', re.DEBUG)
max_repeat 0 65535
  any None
>>>                         

正则表达式'|' 运算符vs每个子表达式的单独运行

  • 这只是答案的一半,它显示了正则表达式编译的内容,但没有显示它是如何针对给定字符串执行的.如果有人知道另一半,请分享! (8认同)

Nik*_* G. 9

https://www.debuggex.com也不错。它是一个在线 Python(以及其他几种语言)调试器,它可以非常清晰地显示匹配和不匹配的内容。如果您需要快速起草正则表达式,这是一个非常好的资源。