如何在正则表达式中跟踪和保存模式?

时间:2015-07-01 02:01:44

标签: python regex

我有以下代码。

text = "#QUESTION Hello, how are you? #ANSWER I am fine."
pattern = re.compile('#QUESTION((.|\s|$)[^#]+)')
matches = pattern.findall(text)

我想从文本变量中提取出#QUESTION Hello, how are you?部分但是,当我在模式下应用正则表达式时,我只获得Hello, how are you?我还要包含#QUESTION }标签,以便它说#QUESTION Hello, how are you?我该怎么做?

1 个答案:

答案 0 :(得分:2)

您可以改变当前表达式,在组中包含“#Question”。

#includes parentheses around the #QUESTION and the rest of the expression)
pattern = re.compile('(#QUESTION(?:(?:.|\s|$)[^#]+))') 

(?: expression)表示您不想跟踪的分组。换句话说,出于表达的目的,这些字符都意味着一起,但你不想单独跟踪它。