假设我有一个字符串'gfgfdAAA1234ZZZuijjk',我想提取'1234'部分。
我只知道在AAA之前的几个字符,以及在ZZZ之后的我感兴趣的部分1234。
使用sed,可以对字符串执行如下操作:
echo "$STRING" | sed -e "s|.*AAA\(.*\)ZZZ.*|\1|"
结果是1234。
如何在Python中做同样的事情?
假设我有一个字符串'gfgfdAAA1234ZZZuijjk',我想提取'1234'部分。
我只知道在AAA之前的几个字符,以及在ZZZ之后的我感兴趣的部分1234。
使用sed,可以对字符串执行如下操作:
echo "$STRING" | sed -e "s|.*AAA\(.*\)ZZZ.*|\1|"
结果是1234。
如何在Python中做同样的事情?
当前回答
使用正则表达式-供进一步参考的文档
import re
text = 'gfgfdAAA1234ZZZuijjk'
m = re.search('AAA(.+?)ZZZ', text)
if m:
found = m.group(1)
# found: 1234
or:
import re
text = 'gfgfdAAA1234ZZZuijjk'
try:
found = re.search('AAA(.+?)ZZZ', text).group(1)
except AttributeError:
# AAA, ZZZ not found in the original string
found = '' # apply your error handling
# found: 1234
其他回答
正则表达式
import re
re.search(r"(?<=AAA).*?(?=ZZZ)", your_text).group(0)
如果your_text中没有“AAA”和“ZZZ”,上述as-is将失败,并出现AttributeError
字符串的方法
your_text.partition("AAA")[2].partition("ZZZ")[0]
如果your_text中不存在"AAA"或"ZZZ",上述函数将返回空字符串。
PS Python挑战?
如果没有匹配则返回其他字符串的一行。 编辑:改进版本使用next函数,如果需要,将“not-found”替换为其他内容:
import re
res = next( (m.group(1) for m in [re.search("AAA(.*?)ZZZ", "gfgfdAAA1234ZZZuijjk" ),] if m), "not-found" )
我的另一个方法来做这个,不太理想,使用regex第二次,仍然没有找到一个更短的方法:
import re
res = ( ( re.search("AAA(.*?)ZZZ", "gfgfdAAA1234ZZZuijjk") or re.search("()","") ).group(1) )
>>> s = '/tmp/10508.constantstring'
>>> s.split('/tmp/')[1].split('constantstring')[0].strip('.')
此外,您可以在波纹函数中找到所有的组合
s = 'Part 1. Part 2. Part 3 then more text'
def find_all_places(text,word):
word_places = []
i=0
while True:
word_place = text.find(word,i)
i+=len(word)+word_place
if i>=len(text):
break
if word_place<0:
break
word_places.append(word_place)
return word_places
def find_all_combination(text,start,end):
start_places = find_all_places(text,start)
end_places = find_all_places(text,end)
combination_list = []
for start_place in start_places:
for end_place in end_places:
print(start_place)
print(end_place)
if start_place>=end_place:
continue
combination_list.append(text[start_place:end_place])
return combination_list
find_all_combination(s,"Part","Part")
结果:
['Part 1. ', 'Part 1. Part 2. ', 'Part 2. ']
你可以使用re模块:
>>> import re
>>> re.compile(".*AAA(.*)ZZZ.*").match("gfgfdAAA1234ZZZuijjk").groups()
('1234,)