python - findall 和正则表达式,得到正确的模式

标签 python regex python-2.7 findall

我正在研究 Magnus Lie Hetland 的书“Beginning Python”第二版,在第 244 页上,他说我的代码中列出的第一个模式应该产生此代码底部列出的所需输出,但事实并非如此't。因此,我尝试了其他几种模式,以尝试获得所需的输出,但它们也不起作用。我检查了这本书的勘误表,发现此页没有任何更正。我正在使用 python 2.7.6。有什么建议吗?

import re

s1 = 'http://www.python.org http://python.org www.python.org python.org .python.org ww.python.org w.python.org wwww.python.org'

# choose a pattern and comment out the other two

# output using Hetland's pattern
pat = r'(http://)?(www\.)?python\.org'
''' [('http://', 'www.'), ('http://', ''), ('', 'www.'), ('', ''), ('', ''), ('', ''), ('', ''), ('', 'www.')] '''

# output using this pattern
# pat = r'http://?www\.?python\.org'
''' ['http://www.python.org'] '''

# output using this pattern
# pat = r'http://?|www\.?|python\.org'
''' ['http://', 'www.', 'python.org', 'www.', 'http://', 'python.org', 'www.', 'python.org', 'python.org', 'python.org', 'python.org', 'python.org', 'www', 'python.org'] '''

print '\n', re.findall(pat, s1)

# desired output
''' ['http://www.python.org', 'http://python.org', 'www.python.org', 'python.org'] '''

最佳答案

如果将前两个可选组设为非捕获组,则该模式有效 (?:...):

pat = r'(?:http://)?(?:www\.)?python\.org'
matches = re.findall(pat, s1)
# ['http://www.python.org', 'http://python.org', 'www.python.org', 'python.org', 'python.org', 'python.org', 'python.org', 'www.python.org']

也就是说,如果这是所需的结果 - 因为模式的更改意味着只有一个捕获组而不是三个...

关于python - findall 和正则表达式,得到正确的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22387868/

相关文章:

java - 使用 .equals 方法进行正则表达式字符串匹配

python - 如何使用正则表达式分隔符来处理特殊情况?

c++ - 自动检测相同的连续 std::string::find() 调用

python - 使用 scipy 在 python 中构建和更新稀疏矩阵

python - 使用 python 简化有理数

python - 蝗虫 : How to invoke the test through an API

python - TensorFlow 的 Print 或 K.print_tensor 不会在损失函数中打印中间张量

Python:如何将构造函数放入 map() 函数中?

Python 3,如何将字符串转换为 "iso-8859-1"以在html中使用

Python 2.7 IDLE 在 Mac OSX 上不断崩溃