如何让正则表达式"吞噬"一个角色?

ale*_*lex 0 php regex

我有一个像这样的文本文件

{word} definition
{another word} another definition {word} they don't have to be on different lines
Run Code Online (Sandbox Code Playgroud)

我正在使用的正则表达式是

    $regex = '/\{([a-z]+?)\}(.+?)\{/i';
Run Code Online (Sandbox Code Playgroud)

然而,这会引起问题,因为它吞下最后一个括号{,然后它将与下一个{在下一个单词中不匹配.

为了演示,我这样做是出于调试目的

echo preg_replace($regex, '<b style="background-color: red;">$1</b><b style="background-color: yellow;">$2</b>', $content);
Run Code Online (Sandbox Code Playgroud)

这是我的输出示例(注意下一个单词中的左括号不存在,因此在正则表达式中不匹配)

<b style="background-color: red;">shrub</b><b style="background-color: yellow;"> Multi stemmed woody plant</b>Abaxial}    side or face away from the axis
Run Code Online (Sandbox Code Playgroud)

如何修改我的正则表达式才能使其工作?谢谢

编辑

非常感谢你的回答.我已经改变了我的正则表达式

$regex = '/\{([a-z\-\s]+?)\}([^\{]+)/i';
Run Code Online (Sandbox Code Playgroud)

我还将研究前瞻性文章.

Mil*_*les 7

对于这种特定情况,您可以:

$regex = '/\{([a-z]+?)\}([^\{]+)/i';
Run Code Online (Sandbox Code Playgroud)

[^\{]表示"匹配任何不是左括号的字符".这也具有不需要{输入结束的优点.

更一般地说,您也可以像其他人提到的那样使用先行断言.