我正在尝试将正向回顾与 Python 中的正则表达式的 If-Then-Else 语法结合起来。
我想做的是解析一些数据,我需要使用两个不同的标记来分割字符串。
我正在尝试做的一个例子:
如果data =“(我想要)一些冰淇淋”
。然后我想在(我想要)
之后分割字符串。
同时,我可能会得到data =“我想要一些冰淇淋”
。在这种情况下,我想在 I
之后分割字符串。
我面临的问题是,我无法使用第一个空格作为查找分隔位置的确定方法,因为 (I Want)
中有一个空格。
使用此处的概念 http://www.regular-expressions.info/conditional.html ,我想创建一个 If-Then-Else 正则表达式,其中包含字符串是否以 (
开头的后视。
这是我到目前为止所拥有的:
(?(?<=(^\())(^(.*?)\)|^(.*?)( ))
如果字符串以 "("
开头,则匹配直到第一个 )
。否则匹配直到第一个空格。
然而,这不起作用。
最佳答案
If string starts with
(
then match until the first)
. Else match until the first space. This doesn't work..
我真的认为没有必要在这里使用 If
-Then
-Else
条件,你可以这样做。
^((?:\([^)]*\)|\S+))
正则表达式:
^ the beginning of the string
( group and capture to \1:
(?: group, but do not capture:
\( '('
[^)]* any character except: ')' (0 or more times)
\) ')'
| OR
\S+ non-whitespace (all but \n, \r, \t, \f, and " ")
) end of grouping
) end of \1
关于python - 如何在 Python 中使用 If-Then-Else 正则表达式进行正向查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20431640/