正则表达式,可以获取带有一些文本的标记

时间:2018-01-19 09:40:02

标签: regex

以下是我的例子:

<w:p>
<w:pPr>
    <w:spacing></w:spacing>
    <w:contextualSpacing/>
    <w:rPr/>
</w:pPr>
<w:r>
    <w:rPr>
        <w:color/>
        <w:rtl w:val="0"/>
    </w:rPr>
    <w:t>Some text</w:t>
</w:r>

<w:r>
    <w:rPr>
        <w:color/>
        <w:rtl/>
    </w:rPr>
    <w:t>My search text</w:t>
</w:r>

<w:r>
    <w:rPr>
        <w:color/>
        <w:rtl/>
    </w:rPr>
    <w:t>Other text</w:t>
</w:r>

我需要使用正则表达式来获取此块:

<w:r>
    <w:rPr>
        <w:color/>
        <w:rtl/>
    </w:rPr>
    <w:t>My search text</w:t>
</w:r>

但我的正则表达总是先<w:r&gt;最后</w:r>。懒惰的量词没有帮助。

那么我怎么能只用“我的搜索文本”来阻止<w:r> </w:r>阻止?

https://regex101.com/r/2Sh68k/2以下是示例

1 个答案:

答案 0 :(得分:1)

这里是修复示例的步骤

<w:r>.+My search text.+<\/w:r>

. .+周围添加非捕获群组无效

<w:r>(?:.)+My search text(?:.)+<\/w:r>

(?!)之前插入否定前瞻.,以防止下一个匹配的字符成为不想要的序列<w:r></w:r>

的开头
<w:r>(?:(?!<w:r>|<\/w:r>).)+My search text(?:(?!<w:r>|<\/w:r>).)+<\/w:r>

updated link