1

私はそのような正規表現を一致させようとしています

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

出力します

?color red ?name Yuri ? ?

コマンドの先頭は常に (? + 少なくとも 1 文字) であり、コマンドの末尾は常に (? + 空白) であることに注意してください。

次の正規表現を使用してみました:

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

ただし、次の入力がある場合:

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

それは一致します:

?name Yuri ? welcome to ?forum Python ?

ただし、個別に一致する必要があります(つまり[?name Yuri ? , ?forum Python ?]

助けてください!繰り返しますが、コマンドは常に ?+文字で始まり ?+空白で終わります

更新 1:

ただし、出力は ['?color red ?name Yuri ? '] そしてそれは ['?color red ?name Yuri ? ? '] (2 つのクエスチョン マーク) 注: ネスティングは無限にできます。つまり、?name ?name ?color ?color ? ? ? ?

したがって、アイデアは ?command ? です。関数呼び出しを表すので、「?add 2 ?multiply 3 3 ? 5 ?」があるとしましょう。-> "?multiply 3 3 ?" を実行する必要があります。これは 9 を返し、それから "?add 2 9(return から得たもの) 5 ?" を実行します。合計すると 16 になります

更新 2:

UPDATE 2からのAvinashの回答は素晴らしいです!

4

1 に答える 1

1

貪欲でない正規表現を使用する必要があります。

>>> 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 ? ']

最後の空白を出力したくない場合は、肯定的な先読みアサーションを追加します。

>>> 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 ? ']

デモ

更新 2:

>>> 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 ? ? ?']

デモ

于 2015-04-13T01:29:31.607 に答える