为什么我的代码在提取字符串时不能在Python正则表达式中工作

2024-10-03 21:27:29 发布

您现在位置:Python中文网/ 问答频道 /正文

试图从字符串中提取字符串和数字,但未按预期执行

s = '''
text1
text2
http://url.com/bla1/blah1/text22
text3
'''
import re
re.findall(r'(^http.*|text\d+)',s)

我的想法是,我不会考虑这条线

['text1', 'text2', 'text22', 'text3']

预期

['text1', 'text2', 'text3']

免责声明 请不要做're.sub(r'http\S+', '', s)'


Tags: 字符串textimportrecomhttpurl数字
3条回答

我怀疑您试图在行中的任何地方找到所有text\d+,除了以http开头的行(否则我想不出额外的http检查是否只想在行的开头text的原因)

如果是这样,您可以使用:^(?!http).*(text\d+)。第一组是你需要的

Python的re.findAll返回捕获组的内容:

s = '''
text1
text2
http://url.com/bla1/blah1/text22
text3
xyz text4
text555
'''
re.findall(r'^(?!http).*(text\d+)', s, flags=re.MULTILINE)
# ['text1', 'text2', 'text3', 'text4', 'text555']
re.findall(r'(^text\d+)',s, flags=re.MULTILINE) Use this code at the place of
re.findall(r'^(?!http).*(text\d+)', s, flags=re.MULTILINE)

尝试使用这一行来检测它是否在字符串的开头,我添加了re.MULTILINE标志,以便它尝试匹配每一行:

print(re.findall('^text\d+',s, flags=re.MULTILINE))

输出:

['text1', 'text2', 'text3']

相关问题 更多 >