如何在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>
完整程序:
import re
reg = re.compile("[a-z]+8?")
str = "ccc8"
print(reg.match(str))
结果:
<_sre.SRE_Match object at 0x00000000031D7ED0>
有人可以告诉我如何实际打印结果吗?
Could anybody tell me how to actually print the result?
推荐答案
您需要在match
函数后添加.group()
,以便它打印匹配的字符串,否则仅显示是否发生匹配.要打印由捕获组捕获的字符,需要将相应的组索引传递给.group()
函数.
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. To print the chars which are captured by the capturing groups, you need to pass the corresponding group index to the .group()
function.
>>> 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 (样式,字符串,标志= 0)
re.match(pattern, string, flags=0)
如果字符串开头的零个或多个字符与正则表达式模式匹配,则返回相应的MatchObject实例.如果字符串与模式不匹配,则返回None;否则返回false.请注意,这与零长度匹配不同.
If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding MatchObject instance. Return None if the string does not match the pattern; note that this is different from a zero-length match.
请注意,即使在MULTILINE模式下,re.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.
这篇关于如何在python 3中打印正则表达式匹配结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!