什么是仅匹配空字符串的正则表达式? [英] What is a regex to match ONLY an empty string?

查看:44
本文介绍了什么是仅匹配空字符串的正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多关于正则表达式匹配潜在空字符串的帖子,但我找不到任何提供匹配空字符串的正则表达式的帖子.

There are lots of posts about regexs to match a potentially empty string, but I couldn't readily find any which provided a regex which only matched an empty string.

我知道 ^ 将匹配任何行的开头,而 $ 将匹配任何行的结尾以及字符串的结尾.因此,/^$/ 比\n"、foobar\n\n"等空字符串匹配的多.

I know that ^ will match the beginning of any line and $ will match the end of any line as well as the end of the string. As such, /^$/ matches far more than the empty string such as "\n", "foobar\n\n", etc.

不过,我会认为 /\A\Z/ 只会匹配空字符串,因为 \A 匹配字符串的开头和 \Z 匹配字符串的结尾.但是,我的测试表明 /\A\Z/ 也将匹配\n".这是为什么?

I would have thought, though, that /\A\Z/ would match just the empty string, since \A matches the beginning of the string and \Z matches the end of the string. However, my testing shows that /\A\Z/ will also match "\n". Why is that?

推荐答案

http://www.regular-expressions.info/anchors.html 在以换行符结尾的字符串"部分下,\Z 通常会在字符串中的最后一个换行符结束之前匹配以换行符结尾.如果只想匹配字符串的结尾,则需要使用\z.此规则的例外是 Python.

As explained in http://www.regular-expressions.info/anchors.html under the section "Strings Ending with a Line Break", \Z will generally match before the end of the last newline in strings that end in a newline. If you want to only match the end of the string, you need to use \z. The exception to this rule is Python.

换句话说,要独占匹配一个空字符串,您需要使用/\A\z/.

In other words, to exclusively match an empty string, you need to use /\A\z/.

这篇关于什么是仅匹配空字符串的正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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