如何在模式中定义可选部件? [关闭]

Here is my content:

<div>something</div>
<div>something else <p>paragraph</p></div>

And this is my pattern:

/<div>([^<]+).*?<\/div>/

As you see, it matches just the text content of div. Now I want to add an optional part to the pattern for p. I mean, I want to get p's value as another capturing group if it exists.

How can I do that?

You can use <div>([^<]+)(<p>(.*?)<\/p>)?<\/div> :

regex demo

for your input :

<div>something</div>
<div>something else <p>paragraph</p></div>

Output

something
something else 
paragraph