Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何打印正则表达式的部分_Python_Regex - Fatal编程技术网

Python 如何打印正则表达式的部分

Python 如何打印正则表达式的部分,python,regex,Python,Regex,我无法打印匹配正则表达式的组件 我正在学习python3,我需要验证命令的输出是否符合我的需要。我有以下短代码: #!/usr/bin/python3 import re text_to_search = ''' 1 | 27 23 8 | 2 | 21 23 8 | 3 | 21 23 8 | 4 | 21 21 21 | 5 | 21 21 21 | 6 | 27 27 27 | 7 | 27 27 27 |

我无法打印匹配正则表达式的组件

我正在学习python3,我需要验证命令的输出是否符合我的需要。我有以下短代码:

#!/usr/bin/python3

import re

text_to_search = ''' 
   1 | 27  23   8 |
   2 | 21  23   8 |
   3 | 21  23   8 |
   4 | 21  21  21 |
   5 | 21  21  21 |
   6 | 27  27  27 |
   7 | 27  27  27 |
'''

pattern = re.compile('(.*\n)*(   \d \| 2[17]  2[137]  [ 2][178] \|)')
matches = pattern.finditer(text_to_search)

for match in matches:
    print (match)
    print ()
    print ('matched to group 0:' + match.group(0))
    print ()
    print ('matched to group 1:' + match.group(1))
    print ()
    print ('matched to group 2:' + match.group(2))
以及以下输出:

<_sre.SRE_Match object; span=(0, 140), match='\n   1 | 27  23   8 |\n   2 | 21  23   8 |\n   3 >

matched to group 0:
   1 | 27  23   8 |
   2 | 21  23   8 |
   3 | 21  23   8 |
   4 | 21  21  21 |
   5 | 21  21  21 |
   6 | 27  27  27 |
   7 | 27  27  27 |

matched to group 1:   6 | 27  27  27 |


matched to group 2:   7 | 27  27  27 |
1)打印(匹配)
仅显示对象的轮廓
match
是一个
SRE\u match
,因此为了从中获取信息,您需要执行类似于
match.group(0)
的操作,这是访问存储在对象中的值

2) 要捕获第1-6行,需要根据以下内容将
(.*\n)*
更改为
((?:.*\n)*)

重复捕获组将只捕获最后一次迭代。在重复组周围放置一个捕获组以捕获所有迭代,或者如果您对数据不感兴趣,则使用非捕获组


3) 要匹配特定的数字,您需要使其更加具体,并在末尾将这些数字包含到一个单独的组中。

您到底想得到什么?每行作为一组?至于你的第二点:重复的捕获组只会捕获最后一次迭代。在重复组周围放置一个捕获组以捕获所有迭代。您是否尝试过使用任何在线regex测试人员/工具分析您的模式?您可能应该问三个单独的问题-这不是讨论论坛或教程。问题2在这里可能有一个副本。问题2可能也有一个副本:]Thx用于回答问题1和问题2。
我不想知道具体的数字。我想确定第一个、第二个和最后一个数字是相等的。在最后一行,它的价值并不重要,对我来说只有平等才重要。