从两个方向解析得到子串

2024-04-26 18:28:50 发布

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

我有很多'字符的字符串,需要提取其中的子字符串:

str = "There is' 'some' Text', and' EXTRACT ME'a'n'd' even' more' 't'ext"

我想从左边得到第5个'之后的子串,从右边得到第8个'之后的子串(向后),这样的结果是:

result = " EXTRACT ME"

我该怎么做?你知道吗


Tags: and字符串textismoreextractsomeresult
3条回答

您可以从左侧或右侧拆分字符串,使用^{}^{}限制拆分的次数:

result = inputstring.split("'", 5)[-1].rsplit("'", 8)[0]

请注意,第二个参数将拆分限制为分别从左侧或右侧计数的第一个n出现。你知道吗

演示:

>>> inputstring = "There is' 'some' Text', and' EXTRACT ME'a'n'd' even' more' 't'ext"
>>> inputstring.split("'", 5)[-1].rsplit("'", 8)[0]
' EXTRACT ME'

不创建临时列表或字符串对象的稍长的解决方案:

s = "There is' 'some' Text', and' EXTRACT ME'a'n'd' even' more' 't'ext"
i = -1
for _ in xrange(5):
  i = s.find("'", i + 1)
  assert i >= 0
j = len(s)
for _ in xrange(8):
  j = s.rfind("'", i, j)
  assert j >= 0
print repr(s[i + 1 : j])  #: 'EXTRACT ME'

这个也很方便:

inputString = re.sub("^([^']*'){5}(.*?)('[^']*){8}$", "\\2", inputString)

相关问题 更多 >