简体   繁体   English

如何在python 3中打印正则表达式匹配结果?

[英]How to print regex match results in python 3?

I was in IDLE, and decided to use regex to sort out a string.我在空闲,并决定使用正则表达式来整理一个字符串。 But when I typed in what the online tutorial told me to, all it would do was print:但是当我输入在线教程告诉我的内容时,它只会打印:

<_sre.SRE_Match object at 0x00000000031D7E68>

Full program:完整程序:

import re
reg = re.compile("[a-z]+8?")
str = "ccc8"
print(reg.match(str))

result:结果:

<_sre.SRE_Match object at 0x00000000031D7ED0>

Could anybody tell me how to actually print the result?有人能告诉我如何实际打印结果吗?

You need to include .group() after to the match function so that it would print the matched string otherwise it shows only whether a match happened or not.您需要在match函数之后包含.group()以便它打印匹配的字符串,否则它仅显示匹配是否发生。 To print the chars which are captured by the capturing groups, you need to pass the corresponding group index to the .group() function.要打印捕获组捕获的字符,您需要将相应的组索引传递给.group()函数。

>>> import re
>>> reg = re.compile("[a-z]+8?")
>>> str = "ccc8"
>>> print(reg.match(str).group())
ccc8

Regex with capturing group.带有捕获组的正则表达式。

>>> reg = re.compile("([a-z]+)8?")
>>> print(reg.match(str).group(1))
ccc

re.match (pattern, string, flags=0)重新匹配(模式,字符串,标志= 0)

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding MatchObject instance.如果字符串开头的零个或多个字符与正则表达式模式匹配,则返回相应的 MatchObject 实例。 Return None if the string does not match the pattern;如果字符串与模式不匹配,则返回 None; note that this is different from a zero-length match.请注意,这与零长度匹配不同。

Note that even in MULTILINE mode, re.match() will only match at the beginning of the string and not at the beginning of each line.请注意,即使在 MULTILINE 模式下, re.match() 也只会匹配字符串的开头,而不是每行的开头。

If you need to get the whole match value , you should use如果您需要获取整个匹配值,则应使用

m = reg.match(r"[a-z]+8?", text)
if m:                          # Always check if a match occurred to avoid NoneType issues
  print(m.group())             # Print the match string

If you need to extract a part of the regex match, you need to use capturing groups in your regular expression.如果需要提取正则表达式匹配的一部分,则需要在正则表达式中使用捕获组 Enclose those patterns with a pair of unescaped parentheses.用一对未转义的括号将这些模式括起来。

To only print captured group results, use Match.groups :要仅打印捕获的组结果,请使用Match.groups

Return a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern.返回一个包含匹配所有子组的元组,从 1 到模式中有多少个组。 The default argument is used for groups that did not participate in the match;默认参数用于未参加比赛的组; it defaults to None.它默认为无。

So, to get ccc and 8 and display only those, you may use因此,要获得ccc8并仅显示那些,您可以使用

import re
reg = re.compile("([a-z]+)(8?)")
s = "ccc8"
m = reg.match(s)
if m:
  print(m.groups()) # => ('ccc', '8')

See the Python demo查看Python 演示

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

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