简体   繁体   中英

Extracting using a string pattern in Regex- Python

Cant we give a string in the Regex? For example, re.compile('((.*)?=<Bangalore>)') , in the below code i have mentioned <Bangalore> but its not displaying.

I want to extract the text before 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)

Desired output: Kathick Kumar, Bangalore

Something like this?

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

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

Use (.*)(?:Bangalore) pattern

>>> 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
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM