Skip to main content
 首页 » 编程设计

python之正则表达式 python

2025年05月04日25zhenyulu

我尝试学习 python3,并且我对正则表达式有一点了解。我为此研究了HOWTO,但我不太了解。此页

    1\d2\D2 
    ^a\w+z$ 

请您参考如下方法:

您可以通过阅读表达式并逐步选择合适的字符来生成示例字符串。

例如,1\d2\D2:

1\d2\D2 -> 1 
^ 1 means a literal number 1 
 
1\d2\D2 -> 17 
 ^^ \d means any digit (0-9).  let's choose 7. 
 
1\d2\D2 -> 172 
   ^ 2 means a literal number 2. 
 
1\d2\D2 -> 172X 
    ^^ \D means anything *but* a digit (0-9).  let's choose X 
 
1\d2\D2 -> 172X2 
      ^ 2 means a literal number 2. 

所以 172X2 将匹配 1\d2\D2

你的下一个 - ^a\w+z$ - 可以有多个长度:

^a\w+z$ 
^ this means we need to be at the start of a line (and we are, so that's cool) 
 
^a\w+z$ -> a 
 ^ a means a literal letter a 
 
^a\w+z$ -> a4 
  ^^ \w means a digit, letter, or "_".  let's choose 4. 
 
^a\w+z$ -> a4 
    ^ + means we can return to whatever is to the left, if we want, so let's do that... 
 
^a\w+z$ -> a4Q 
  ^^ \w means a digit, letter, or "_".  let's choose Q. 
 
^a\w+z$ -> a4Q 
    ^ + means we can return to whatever is to the left, if we want, so let's do that... 
 
^a\w+z$ -> a4Q1 
  ^^ \w means a digit, letter, or "_".  let's choose 1. 
 
^a\w+z$ -> a4Q1 
    ^ + means we can return to whatever is to the left, but now let's stop 
 
^a\w+z$ -> a4Q1z 
     ^ z means a literal letter z 
 
^a\w+z$ -> a4Q1z 
      ^ $ means we must be at the end of the line, and we are (and so cannot add more) 

所以 a4Q1z 将与 ^a\w+z$ 匹配。 a4z 也是如此(您可以查看...)

请注意,* 与 + 类似,您可以跳回并重复,但也这意味着您可以完全跳过要执行的内容左边(换句话说,+ 表示“至少重复一次”,而 * 表示“重复零次或多次”(“零”表示跳过))。

更新:

[abc] 表示选择a、b 或c 中的任意一个。

x{2,3}表示将x加2到3次(类似+但有次数限制)。所以,xx 或 xxx。

\1 有点复杂。您需要找到第一组(因为编号为 1)括号内的内容并添加它。因此,例如,如果您从左到右工作并为 选择 23,则 (\d+)\1 将匹配 2323 (\d+).