正则表达式匹配除给定正则表达式之外的所有内容 [英] Regular expression matching everything except a given regular expression

查看:73
本文介绍了正则表达式匹配除给定正则表达式之外的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出一个正则表达式来匹配任何不以 mpeg 开头的字符串.对此的概括是匹配任何不以给定正则表达式开头的字符串.

I am trying to figure out a regular expression which matches any string that doesn't start with mpeg. A generalization of this is matching any string which doesn't start with a given regular expression.

我尝试了如下:

[^m][^p][^e][^g].* 

问题在于它要求字符串中至少有 4 个字符.我无法找到一种很好的方法来处理这个问题,也找不到一种通用的方法来处理这个问题.

The problem with this is that it requires at least 4 characters to be present in the string. I was not able to figure out a good way to handle this and a generalized way to handle this in a general purpose manner.

我将在 Python 中使用它.

I will be using this in Python.

推荐答案

^(?!mpeg).*

这使用负前瞻来仅匹配开头不匹配 mpeg 的字符串.本质上,它要求字符串开头的位置不能是一个位置,如果我们开始匹配正则表达式 mpeg,我们可以成功匹配"——从而匹配任何不以 mpeg 开头的内容,并且不匹配任何匹配的内容.

This uses a negative lookahead to only match a string where the beginning doesn't match mpeg. Essentially, it requires that "the position at the beginning of the string cannot be a position where if we started matching the regex mpeg, we could successfully match" - thus matching anything which doesn't start with mpeg, and not matching anything that does.

但是,我很好奇您使用它的上下文 - 除了正则表达式之外,可能还有其他选项会更有效或更易读,例如...

However, I'd be curious about the context in which you're using this - there might be other options aside from regex which would be either more efficient or more readable, such as...

if not inputstring.startswith("mpeg"):

这篇关于正则表达式匹配除给定正则表达式之外的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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