在Regex-Python中使用字符串模式进行提取

2024-04-25 13:37:54 发布

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

我们不能在正则表达式中给出一个字符串吗?例如,re.compile('((.*)?=<Bangalore>)'),在下面的代码中我提到了<Bangalore>,但它没有显示。你知道吗

我想在班加罗尔之前提取文本。你知道吗

import re

regex = re.compile('((.*)?=<>)')

line = ("Kathick Kumar, Bangalore who was a great person and lived from 29th 

March 1980 - 21 Dec 2014")

result = regex.search(line)

print(result)

期望输出:Kathick Kumar,班加罗尔


Tags: 字符串代码文本importrelineresultregex
2条回答

使用(.*)(?:Bangalore)模式

>>> line = ("Kathick Kumar, Bangalore who was a great person and lived from 29thMarch 1980 - 21 Dec 2014")
>>> import re
>>> regex = re.compile('(.*)(?:Bangalore)')
>>> result = regex.search(line)
>>> print(result.group(0))
Kathick Kumar, Bangalore
>>> 

像这样的?你知道吗

import re
regex = re.compile('(.*Bangalore)')
result = regex.search(line)

>>> print result.groups()
('Kathick Kumar, Bangalore',)

相关问题 更多 >