Python 2.7 Python-在字符串中查找文本,然后在前面抓取文本X空格?
鉴于此——Python 2.7 Python-在字符串中查找文本,然后在前面抓取文本X空格?,python-2.7,Python 2.7,鉴于此—— string = "this is text. here is what I want. stop." 我想在字符串中搜索单词text,然后向前移动,直到找到单词stop。如果这看起来很奇怪,我正在进行SeleniumWebDriver测试,以从页面源获取文本(源代码没有正确的ID/名称/等等,有点痛苦)。谢谢 代码片段: import re string = "this is text. here is what I want. stop." match = re.match("
string = "this is text. here is what I want. stop."
我想在字符串中搜索单词text
,然后向前移动,直到找到单词stop
。如果这看起来很奇怪,我正在进行SeleniumWebDriver测试,以从页面源获取文本(源代码没有正确的ID/名称/等等,有点痛苦)。谢谢 代码片段:
import re
string = "this is text. here is what I want. stop."
match = re.match("^.*text(.*)stop.*$", string)
print(match.groups()[0])
输出:
. here is what I want.
以下是您想要的:
>>> string = "this is text. here is what I want. stop."
>>> x = re.split('(\W)', string)
>>> x
['this', ' ', 'is', ' ', 'text', '.', '', ' ', 'here', ' ', 'is', ' ', 'what', ' ', 'I', ' ', 'want', '.', '', ' ', 'stop', '.', '']
>>> for k in range(0, len(x)):
... if x[k] == 'text':
... cur = 'text'
... arr = []
... while cur != 'stop':
... cur = x[k+1]
... k+=1
... arr.append(cur)
... break
...
>>> arr
['.', '', ' ', 'here', ' ', 'is', ' ', 'what', ' ', 'I', ' ', 'want', '.', '', ' ', 'stop']
>>> ''.join(arr)
'. here is what I want.'
>>>
当的循环到达'text'
时,它会一直运行,直到到达停止点,然后停止