假设我有一个字符串'gfgfdAAA1234ZZZuijjk',我想提取'1234'部分。

我只知道在AAA之前的几个字符,以及在ZZZ之后的我感兴趣的部分1234。

使用sed,可以对字符串执行如下操作:

echo "$STRING" | sed -e "s|.*AAA\(.*\)ZZZ.*|\1|"

结果是1234。

如何在Python中做同样的事情?


当前回答

Python 3.8中保证文本包含子字符串的一行代码:

text[text.find(start:='AAA')+len(start):text.find('ZZZ')]

其他回答

如果你想寻找多次出现的情况。

content ="Prefix_helloworld_Suffix_stuff_Prefix_42_Suffix_andsoon"
strings = []
for c in content.split('Prefix_'):
    spos = c.find('_Suffix')
    if spos!=-1:
        strings.append( c[:spos])
print( strings )

或者更快:

strings = [ c[:c.find('_Suffix')] for c in content.split('Prefix_') if c.find('_Suffix')!=-1 ]

使用正则表达式-供进一步参考的文档

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

在python中,可以使用正则表达式(re)模块中的findall方法从字符串中提取子字符串。

>>> import re
>>> s = 'gfgfdAAA1234ZZZuijjk'
>>> ss = re.findall('AAA(.+)ZZZ', s)
>>> print ss
['1234']
import re
print re.search('AAA(.*?)ZZZ', 'gfgfdAAA1234ZZZuijjk').group(1)

Python 3.8中保证文本包含子字符串的一行代码:

text[text.find(start:='AAA')+len(start):text.find('ZZZ')]