regex 是否存在匹配嵌套短语的正则表达式模式?

rn0zuynd  于 2023-08-08  发布在  其他
关注(0)|答案(2)|浏览(63)

有了字符串"The cat is (black|white)",我可以使用模式/\((.*?)\|.*?\)/并替换字符串中的第一个匹配项,得到结果短语"The cat is black"。例如在PHP中,使用preg_replace('/\((.*?)\|.*?\)/', '$1', $phrase)
现在,我想扩展模式,以获得相同的结果字符串,即"The cat is black",也是从开始字符串"The (cat is (black|white)|dog is (black|white))"
这种模式应该对两种类型的短语都有效。
有可能吗?
谢啦,谢啦

xsuvu9jc

xsuvu9jc1#

这个问题并不适合直接使用正则表达式解决。然而,通过编写一个简短的递归函数来扩展模式所描述的替代短语,很容易解决这个问题。
你没有用语言标记这个问题,所以我将提供一个Python实现的例子。您应该能够将其翻译为您选择的语言。
给定函数

def pattern2alternates(pattern: str) -> Iterator[str]:
    try:
        # Attempt to find a subpattern enclosed in parentheses.
        open_pos = pattern.index("(")
        close_pos = pattern.rindex(")")
    except ValueError:
        yield pattern
        return
    
    prefix = pattern[:open_pos]
    middle = pattern[open_pos+1:close_pos]
    suffix = pattern[close_pos+1:]
    
    # Split the pattern on each '|' not enclosed by parentheses.
    for alt in re.split(r"\|(?![^\(]+\))", middle):
        # Recursively expand subpatterns for the current alternate.
        for sub in pattern2alternates(alt):
            yield f"{prefix}{sub}{suffix}"

字符串
您可以将输入模式扩展为

>>> input_pattern = "The (cat is (black|white)|dog is (black|white))"
>>> print(list(pattern2alternates(input_pattern)))
['The cat is black', 'The cat is white', 'The dog is black', 'The dog is white']

gtlvzcf8

gtlvzcf82#

我用PHP解决了这个问题:

function unfoldPattern($string)
{
    $result = preg_replace('/\(([^(]*?)\|.*?\)/', '$1', $string);
    
    if ($result != $string)
    {
        return $this->unfoldPattern($result);
    }
    
    else
    {
        return $result;
    }
}

字符串

相关问题