Skip to main content
 首页 » 编程设计

python之如何在 Python 中对 If-Then-Else 正则表达式使用正向后视

2024年11月01日34zhwl

我正在尝试将正向回顾与 Python 中正则表达式的 If-Then-Else 语法相结合。

我要做的是解析一些数据,我需要使用两个不同的标记来拆分字符串。

我正在尝试做的一个例子: 如果 data = "(我想要)一些冰淇淋"。然后我想在 (I want) 之后拆分字符串。 同时,我可能会得到 data = "I want some ice cream"。在这种情况下,我想在 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