将Perl正则表达式转换为Python正则表达式
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了将Perl正则表达式转换为Python正则表达式,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2072字,纯文字阅读大概需要3分钟。
内容图文
我在将Perl正则表达式转换为Python时遇到了麻烦.我想要匹配的文本具有以下模式:
Author(s) : Firstname Lastname Firstname Lastname Firstname Lastname Firstname Lastname
在perl中我能够匹配这个并提取作者
/Author\(s\) :((.+\n)+?)/
当我尝试
re.compile(r'Author\(s\) :((.+\n)+?)')
在Python中,它匹配第一个作者两次并忽略其余的.
谁能解释我在这里做错了什么?
解决方法:
你可以这样做:
# find lines with authors
import re
# multiline string to simulate possible input
text = '''
Stuff before
This won't be matched...
Author(s) : Firstname Lastname
Firstname Lastname
Firstname Lastname
Firstname Lastname
Other(s) : Something else we won't match
More shenanigans....
Only the author names will be matched.
'''
# run the regex to pull author lines from the sample input
authors = re.search(r'Author\(s\)\s*:\s*(.*?)^[^\s]', text, re.DOTALL | re.MULTILINE).group(1)
上面的正则表达式匹配起始文本(作者,空格,冒号,空格),它通过匹配后面以空格开头的所有行给出了下面的结果:
'''Firstname Lastname
Firstname Lastname
Firstname Lastname
Firstname Lastname
'''
然后,您可以使用以下正则表达式对这些结果中的所有作者进行分组
# grab authors from the lines
import re
authors = '''Firstname Lastname
Firstname Lastname
Firstname Lastname
Firstname Lastname
'''
# run the regex to pull a list of individual authors from the author lines
authors = re.findall(r'^\s*(.+?)\s*$', authors, re.MULTILINE)
哪个给出了作者列表:
['Firstname Lastname', 'Firstname Lastname', 'Firstname Lastname', 'Firstname Lastname']
组合示例代码:
text = '''
Stuff before
This won't be matched...
Author(s) : Firstname Lastname
Firstname Lastname
Firstname Lastname
Firstname Lastname
Other(s) : Something else we won't match
More shenanigans....
Only the author names will be matched.
'''
import re
stage1 = re.compile(r'Author\(s\)\s*:\s*(.*?)^[^\s]', re.DOTALL | re.MULTILINE)
stage2 = re.compile('^\s*(.+?)\s*$', re.MULTILINE)
preliminary = stage1.search(text).group(1)
authors = stage2.findall(preliminary)
这使作者成为:
['Firstname Lastname', 'Firstname Lastname', 'Firstname Lastname', 'Firstname Lastname']
成功!
内容总结
以上是互联网集市为您收集整理的将Perl正则表达式转换为Python正则表达式全部内容,希望文章能够帮你解决将Perl正则表达式转换为Python正则表达式所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。