python - 如何在 Python 中使用 If-Then-Else 正则表达式进行正向查找

标签 python regex

我正在尝试将正向回顾与 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

参见Live demo

关于python - 如何在 Python 中使用 If-Then-Else 正则表达式进行正向查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20431640/

相关文章:

ruby - 在 Ruby 中标记字符串的更好方法?

python - Pandas:如何基于扩展分位数创建类别?

java - 如何在replaceregexp中指定属性

C++11 正则表达式匹配不以句点结尾的完整单词?

python - 带列表的高效正则表达式

regex - 用于提取多行 block 的 perl 正则表达式

c# - 用于复杂密码验证的正则表达式

python - python 中的 dsearchn 等效项

Python 使用 Graph API 和 Office365-REST-Python-Client 发送电子邮件

python - 使用 Python 和 OpenCV 的通用填充形状