正则表达式将 li 与 ul 包裹在一起


regex wrap li with ul

我需要用ul标签包装多组li标签。下面是一个示例:

<text>
<p>Today is a nice day</p>
<li>This is line one</li>
<li>This is line two</li>
<li>This is line three</li>
</text>
<text>
<p>Today is also a nice day</p>
<li>This is also line one</li>
<li>This is also line two</li>
<li>This is also line three</li>
</text>

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

/(<li>.*?<'/li>)+/g

当我尝试将所选字符串替换为:

<ul>$1</ul> 

我得到以下信息:

<text>
<p>Today is a nice day</p>
<ul><li>This is line one</li></ul>
<ul><li>This is line two</li></ul>
<ul><li>This is line three</li></ul>
</text>
<text>
<p>Today is also a nice day</p>
<ul><li>This is also line one</li></ul>
<ul><li>This is also line two</li></ul>
<ul><li>This is also line three</li></ul>
</text>

以下是我希望结果的样子:

<text>
<p>Today is a nice day</p>
<ul><li>This is line one</li></ul>
<ul><li>This is line two</li></ul>
<ul><li>This is line three</li></ul>
</text>
<text>
<p>Today is also a nice day</p>
<ul>
<li>This is also line one</li>
<li>This is also line two</li>
<li>This is also line three</li>
</ul>
</text>

您必须在一次匹配中匹配所有<il>标签,因此您需要使用某种多行模式: s修饰符使.与换行符匹配:

/(</p><li>.*?</li></text>)+/is

另请查看此问题/答案