【发布时间】:2010-01-02 06:35:51
【问题描述】:
我如何使用正则表达式来匹配两个字符串之间的文本,这两个字符串本身包含在两个其他字符串中,并且内部和外部封闭字符串之间有任意数量的文本?
例如,我有这样的文字:
outer-start 一些文本 inner-start text-that-i-want inner-end 一些更多文字外端
在这种情况下,我想要 text-that-i-want,因为它位于 inner-start 和 inner-end 之间,它们位于 outer-start 和 outer-end 之间。
如果我有
一些文本 inner-start text-that-i-want inner-end 一些文本 outer-end强>
那么我不想要 text-that-i-want,因为虽然它在 inner-start 和 inner-end 之间, 没有 outer-start 包围这些字符串。
同样,如果我有
outer-start 一些文本 text-that-i-want inner-end 一些更多文本 outer-end强>
再一次,我不想要text-that-i-want,因为没有封闭的inner-start,虽然有封闭的outer -start 和 outer-end 字符串。
假设 outer-start、inner-start、inner-end 和 outer-end 只会曾经被用于封闭/分隔的目的。
我认为我可以通过执行两遍正则表达式匹配来做到这一点,即查找 outer-start 和 outer-end 之间的任何数据,然后在该数据查找 inner-start 和 inner-end 之间的任何文本(如果确实存在这些字符串),但我想知道它是否可以一次性完成.
【问题讨论】:
-
真实示例而不是这些“外部开始”占位符可能会为您提供更好的答案。
标签: regex language-agnostic match nested