永远不会被任何东西匹配的正则表达式 [英] A Regex that will never be matched by anything

查看:29
本文介绍了永远不会被任何东西匹配的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这听起来可能是个愚蠢的问题,但我与一些开发人员同事进行了长时间的交谈,这听起来很有趣.

This might sound like a stupid question, but I had a long talk with some of my fellow developers and it sounded like a fun thing to think of.

所以;你的想法是什么 - 一个正则表达式是什么样的,它永远不会被任何字符串匹配!

So; what's your thought - what does a Regex look like, that will never be matched by any string, ever!

编辑:为什么我想要这个?嗯,首先是因为我觉得考虑这样的表达式很有趣,其次是因为我需要它来编写脚本.

Edit: Why I want this? Well, firstly because I find it interesting to think of such an expression and secondly because I need it for a script.

在该脚本中,我将字典定义为 Dictionary.如您所见,这包含一个字符串和一个表达式.

In that script I define a dictionary as Dictionary<string, Regex>. This contains, as you see, a string and an expression.

基于那本字典,我创建了所有方法都使用这本字典作为他们应该如何工作的唯一参考,其中一个将正则表达式与解析的日志文件进行匹配.

Based on that dictionary I create methods that all use this dictionary as only reference on how they should do their work, one of them matches the regexes against a parsed logfile.

如果一个表达式匹配,另一个Dictionary被添加一个由表达式返回的值.因此,为了捕获与字典中的表达式不匹配的任何日志消息,我创建了一个名为unknown"的新组.

If an expression is matched, another Dictionary<string, long> is added a value that is returned by the expression. So, to catch any log-messages that are not matched by an expression in the dictionary I created a new group called "unknown".

向该组添加与其他任何内容不匹配的所有内容.但是为了防止未知"表达式与日志消息不匹配(偶然),我必须创建一个绝对不会匹配的表达式,无论我给它什么字符串.

To this group everything that didn't match anything other is added. But to prevent the "unknown"-expression to mismatch (by accident) a log-message, I had to create an expression that is most certainly never matched, no matter what string I give it.

因此,对于这个不是真正的问题",您有我的理由......

Thus, there you have my reason for this "not a real question"...

推荐答案

这个其实很简单,虽然要看实现/flags*:

$a

将匹配字符串末尾的字符 a.祝你好运.

Will match a character a after the end of the string. Good luck.

警告:
这个表达式很昂贵——它会扫描整行,找到行尾锚点,然后才找不到 a 并返回否定匹配.(有关详细信息,请参阅下面的评论.)

WARNING:
This expression is expensive -- it will scan the entire line, find the end-of-line anchor, and only then not find the a and return a negative match. (See comment below for more detail.)

* 本来我没有考虑多行模式正则表达式,其中 $ 也匹配行尾.事实上,它会匹配换行符之前的空字符串,所以像a这样的普通字符永远不会出现在$之后.

* Originally I did not give much thought on multiline-mode regexp, where $ also matches the end of a line. In fact, it would match the empty string right before the newline, so an ordinary character like a can never appear after $.

这篇关于永远不会被任何东西匹配的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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