我有一个格式字符串:
my_string = 'hello|foo world|foo how|bar are|bar you|bar today|foo'
我想返回一个列表,其中foo后面的所有连续单词都分组在同一个字符串中,但中间有"| bar"单词的单词在单独的字符串中.如果我try 重复前瞻:
re.findall(r'(\w+(?=\|foo\b))+',my_string)
退货
['hello', 'world', 'today']
但我想回来的是
['hello world', 'today']
因为"hello"和"world"并没有被一个非foo单词隔开.
在我真正的问题中,后跟"foo"的单词序列在正在搜索的字符串中出现的次数是未知的,"bar"可能是几种不同的模式.
我可以通过几个替换来解决这个问题,首先用拆分指示器替换所有非foo模式,然后在此基础上拆分,然后删除foo和剥离空间:
bars_removed = re.sub('(\w+\|(?!foo)[a-z]+ )+','split_string',my_string)
only_foo_words = [re.sub('\|foo','',x).strip() for x in bars_removed.split('split_string')]
which 退货 the desired result, but I feel like there's a way to do this using findall or maybe finditer that I'm missing.