简体   繁体   English

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

[英]How can I debug a regular expression in Python?

Is there a way to debug a regular expression in Python?有没有办法在 Python 中调试正则表达式? And I'm not referring to the process of trying and trying till they work :)而且我不是指尝试和尝试直到它们起作用的过程:)

Here is how regexes can be debugged in Perl:下面是在 Perl 中调试正则表达式的方法:


use re 'debug';

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

The code above produces the following output on my computer when ran:运行时,上面的代码在我的计算机上产生以下输出:


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+)"

https://www.debuggex.com is also pretty good. https://www.debuggex.com也不错。 It's an online Python (and a couple more languages) debugger, which has a pretty neat visualization of what does and what doesn't match.它是一个在线 Python(和更多语言)调试器,它对匹配和不匹配的内容进行了非常简洁的可视化。 A pretty good resource if you need to draft a regexp quickly.如果您需要快速起草正则表达式,这是一个非常好的资源。

为什么不使用一些 regEx 工具(我通常使用Regulator )并在那里测试正则表达式,当您满意时,只需将其复制/粘贴到您的代码中。

Not sure about doing such a thing directly in Python, but I could definitely suggest using a RegEx editor tool.不确定直接在 Python 中做这样的事情,但我绝对可以建议使用 RegEx 编辑器工具。 That's likely to be your best bet anyway.无论如何,这可能是您最好的选择。 Personally, I've used The Regulator and found it to very helpful.就我个人而言,我使用过The Regulator并发现它非常有帮助。 Some others are listed in this SO thread .其他一些列在此 SO 线程中

类似于已经提到的,还有Regexbuddy

I quite often use RegexPal for quick checks (an online regular expression prototyper).我经常使用RegexPal进行快速检查(一个在线正则表达式原型)。 It has a lot of the common expressions listed along with a simple expression.它列出了许多常用表达式以及一个简单的表达式。 Very handy when you don't have a dedicated tool and just need a quick way to work out a somple regex.当您没有专用工具并且只需要一种快速的方法来计算简单的正则表达式时非常方便。

What RegexBuddy has that the other tools don't have is a built-in debugger that shows you the entire matching process of both successful and failed match attempts. RegexBuddy 拥有而其他工具没有的是一个内置调试器,它向您显示成功和失败的匹配尝试的整个匹配过程。 The other tools only show the final result (which RegexBuddy can show too).其他工具只显示最终结果(RegexBuddy 也可以显示)。

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

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