python - 使用正则表达式 re.search 和 re.compile 的问题

标签 python regex web-scraping syntax-error

堆栈溢出用户向我展示了 https://pythex.org/它允许您构建和测试正则表达式。

我已经成功地只写了表达式,但是当涉及到在 python 中实际使用它时,re.模块我很困惑。

我不明白的是什么时候用.compile,什么时候做re.search -->

例如,如果我搜索括号内的文本并且有多个文本,我认为我应该使用 .group[x] 其中 x 是您要返回的项目的索引

示例

pattern = re.compile(r'View All \((\d*)\)')
number = pattern.search(data).group(2);

据我了解,如果我有以下内容,则 number_connections 变量在打印时将是
View All (8) View All (16) View All (12)

结果
Print number
16

我不明白的是:当您要查找的文本不止一次出现时,您如何遍历它们,以及如何计算有多少?
For example: number.count() would return, found 3
for i in number: (this doesn't work because match is a regular expression object???)
    print i    

但是,当正则表达式中只有您要查找的文本之一时会发生什么?

示例

正则表达式:
模式 = re.compile('[a-zA-Z]\s[a-zA-Z]/[a-zA-Z]/[a-zA-Z]')
电子邮件 = pattern.search(data).group(1);

结果
data: "email-id":"FisrtName LastName/Australia/ABC"}]</p></body></html>
should return: firstname lastname/Australia/ABC

页面上可能有也可能不超过一个 - 在这种情况下,始终使用 result[0] 将不起作用,因为页面上可能只有一个电子邮件地址实例。

现在我意识到我的语法显然是错误的,但这样做也给了我以下信息,所以我正在寻找有关如何正确使用正则表达式的指导,一旦我使用 https://pythex.org/ 构建了它。 :
email = pattern.search(data)
print email

<_sre.SRE_Match object at 0x0553B090>

最佳答案

在我看来,您正处于使用 Python 正则表达式的阶段,您需要阅读一些文档或完整的教程,而不是尝试从不连贯的部分中获取知识。

无论您是否编译正则表达式,您都可以访问完全相同的匹配项。

报价 Jan Goyvaerts ,RegexBuddy 的作者和正则表达式食谱的合著者:

If you want to use the same regular expression more than once, you should compile it into a regular expression object. Regular expression objects are more efficient, and make your code more readable. To create one, just call re.compile(regex) or re.compile(regex, flags). The flags are the matching options described above for the re.search() and re.match() functions.

The regular expression object returned by re.compile() provides all the functions that the re module also provides directly: search(), match(), findall(), finditer(), sub() and split(). The difference is that they use the pattern stored in the regex object, and do not take the regex as the first parameter. re.compile(regex).search(subject) is equivalent to re.search(regex, subject).



对于多个匹配,您可以使用 findallfinditer (更多细节在同一页)。

关于python - 使用正则表达式 re.search 和 re.compile 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23987543/

相关文章:

python - sympy.plotting.plot3d 不绘制常量函数

python - 如何在python中循环列表?

regex - unicode 上的字捕获失败错误,如何修复 5.10

正则表达式一个或多个 vs n+1 匹配

excel - 使用 unicode 字符从本地 HTML 中抓取表格

python - Mersenne Twister 在 Python 中的开源实现?

python - 给定条件的矩阵上的 Numpy 高级索引

java - 在java中替换特殊单词的最佳方法

python - 关于数据类型的 BeautifulSoup 代码问题

python - 如何使用 pandas 和 beautiful soup 来抓取多个网页地址上的表格?