使用正则表达式匹配两个字符串之间的字符串,同时排除字符串 [英] Using regex to match string between two strings while excluding strings

查看:60
本文介绍了使用正则表达式匹配两个字符串之间的字符串,同时排除字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上一个问题之后,我在其中问:

如何使用正则表达式来匹配两个字符串之间的文本,其中这两个字符串本身包含两个其他字符串,内部和外部封闭字符串之间有任意数量的文本?

How can I use a regular expression to match text that is between two strings, where those two strings are themselves enclosed two other strings, with any amount of text between the inner and outer enclosing strings?

我得到了这个答案:

/outer-start.*?inner-start(.*?)inner-end.*?outer-end/

我现在想知道如何从外部封闭字符串和内部封闭字符串之间的文本中排除某些字符串.

I would now like to know how to exclude certain strings from the text between the outer enclosing strings and the inner enclosing strings.

例如,如果我有这样的文字:

For example, if I have this text:

outer-start 一些文字 inner-start text-that-i-want inner-end some更多文字外端

outer-start some text inner-start text-that-i-want inner-end some more text outer-end

我希望一些文字"和更多文字"中不包含不需要的"一词.

I would like 'some text' and 'some more text' not to contain the word 'unwanted'.

换句话说,这没问题:

outer-start 一些想要的文本 inner-start text-that-i-want inner-end一些更多想要的文本外端

outer-start some wanted text inner-start text-that-i-want inner-end some more wanted text outer-end

但这不行:

outer-start 一些不需要的文本 inner-start text-that-i-want inner-end一些不需要的文本外端

outer-start some unwanted text inner-start text-that-i-want inner-end some more unwanted text outer-end

或者进一步解释一下,上面上一个答案中外分隔符和内分隔符之间的表达应该排除不需要的"这个词.

Or to explain further, the expression between outer and inner delimiters in the previous answer above should exclude the word 'unwanted'.

使用正则表达式容易匹配吗?

Is this easy to match using regexes?

推荐答案

将第一个和最后一个(但不是中间).*? 替换为 (?:(?!unwanted).)*?.(其中 (?:...) 是一个非捕获组,而 (?!...) 是一个负面的前瞻.)

Replace the first and last (but not the middle) .*? with (?:(?!unwanted).)*?. (Where (?:...) is a non-capturing group, and (?!...) is a negative lookahead.)

然而,这很快就会在任何实际(而不是示例)使用中以极端情况和警告告终,并且如果您询问您真正在做什么(使用真实示例,即使它们是简化的,而不是示例),您可能会得到更好的答案.

However, this quickly ends up with corner cases and caveats in any real (instead of example) use, and if you would ask about what you're really doing (with real examples, even if they're simplified, instead of made up examples), you'll likely get better answers.

这篇关于使用正则表达式匹配两个字符串之间的字符串,同时排除字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆