如何匹配嵌套字符串而不是单独的字符串

How to match nested strings and not separate string

我正在尝试匹配正则表达式

hello ?color red ?name Yuri ? ? to the forum

会输出

?color red ?name Yuri ? ?

注意命令的开头总是(?+至少一个字母),命令的结尾总是(?+空space)

我尝试使用以下正则表达式:

/\?[^ ](.)*\?/g

但是,如果我们有这样的输入:

hello ?name Yuri ? welcome to ?forum Python ? It's awesome!

它匹配:

?name Yuri ? welcome to ?forum Python ?

但是,它应该单独匹配(即 [?name Yuri ? , ?forum Python ?]

请帮忙!同样,命令总是以 ?+letter 开头并以 ?+whitespace

结尾

更新 1:

但是,输出是 ['?color red ?name Yuri ? '] 应该是 ['?color red ?name Yuri ? ? '](两个问号) 注意嵌套可以是无限的,即 ?name ?name ?color ?color ? ? ? ?

所以这个想法是有 ?command ?代表函数调用,所以假设我们有“?加2?乘3 3?5?” -> 它应该执行 "?multiply 3 3 ?"其中 returns 9,然后它执行“?add 2 9(我们从 return 得到的)5?”加起来是 16

更新 2:

更新 2 中 Avinash 的回答非常棒!

您需要使用非贪婪正则表达式。

>>> import re
>>> s = "hello ?name Yuri ? welcome to ?forum Python ? It's awesome!"
>>> re.findall(r'\?[a-zA-Z].*?\?\s', s)
['?name Yuri ? ', '?forum Python ? ']

如果你不想打印最后一个空 space 然后添加一个积极的先行断言。

>>> re.findall(r'\?[a-zA-Z].*?\?(?=\s)', s)
['?name Yuri ?', '?forum Python ?']

更新:

>>> re.findall(r'\?[A-Za-z](?:\?[^?\n]*\?|[^?\n])*?\?\s', 'hello ?color red ?name Yuri ? ? to the forum')
['?color red ?name Yuri ? ? ']
>>> re.findall(r'\?[A-Za-z](?:\?[^?\n]*\?|[^?\n])*?\?\s', "hello ?name Yuri ? welcome to ?forum Python ? It's awesome!")
['?name Yuri ? ', '?forum Python ? ']

DEMO

更新二:

>>> import regex
>>> regex.findall(r'\?(?:(?R)|[^?])*\?', 'hello ?color ?size 22 red ?name Yuri ? ? ? ')
['?color ?size 22 red ?name Yuri ? ? ?']
>>> regex.findall(r'\?(?=\S)(?:(?R)|[^?])*\?(?=\s)', 'hello ?color ?size 22 red ?name Yuri ? ? ? ')
['?color ?size 22 red ?name Yuri ? ? ?']

DEMO