正则表达式中的\ z和\ Z之间有什么区别?何时以及如何使用它? [英] Whats the difference between \z and \Z in a regular expression and when and how do I use it?

查看:730
本文介绍了正则表达式中的\ z和\ Z之间有什么区别?何时以及如何使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 http://java .sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html :

\Z  The end of the input but for the final terminator, if any
\z  The end of the input

但是实际上这是什么意思呢?当我使用\ Z或\ z时,您能举个例子吗?

But what does it mean in practice? Can you give me an example when I use either the \Z or \z.

在我的测试中,我认为"StackOverflow\n".matches("StackOverflow\\z")将返回true,而"StackOverflow\n".matches("StackOverflow\\Z")返回false.但是实际上两者都返回false.错误在哪里?

In my test I thought that "StackOverflow\n".matches("StackOverflow\\z") will return true and "StackOverflow\n".matches("StackOverflow\\Z") returns false. But actually both return false. Where is the mistake?

推荐答案

即使\Z$仅在字符串的末尾匹配(当 插入符和美元在嵌入式换行符处匹配的选项是 关闭),只有一种例外.如果字符串以换行符结尾, 那么\Z$将在该换行符之前的位置匹配, 而不是字符串的末尾.

Even though \Z and $ only match at the end of the string (when the option for the caret and dollar to match at embedded line breaks is off), there is one exception. If the string ends with a line break, then \Z and $ will match at the position before that line break, rather than at the very end of the string.

此增强"功能是Perl引入的,并被许多正则表达式复制 各种口味,包括Java,.NET和PCRE.在Perl中,当阅读一行时 从文件中得到的字符串将以换行符结尾.读 文件中带有文本"joe"的一行将产生字符串joe \ n. 应用于此字符串时,^[a-z]+$\A[a-z]+\Z都将 匹配乔".

This "enhancement" was introduced by Perl, and is copied by many regex flavors, including Java, .NET and PCRE. In Perl, when reading a line from a file, the resulting string will end with a line break. Reading a line from a file with the text "joe" results in the string joe\n. When applied to this string, both ^[a-z]+$ and \A[a-z]+\Z will match "joe".

如果只想在字符串的绝对结尾处进行匹配,请使用 \z(小写字母z代替大写字母Z). \A[a-z]+\z不 匹配乔\ n. \z在换行符之后匹配,但不匹配 通过角色分类.

If you only want a match at the absolute very end of the string, use \z (lower case z instead of upper case Z). \A[a-z]+\z does not match joe\n. \z matches after the line break, which is not matched by the character class.

http://www.regular-expressions.info/anchors.html

我阅读此"StackOverflow\n".matches("StackOverflow\\z")的方式应返回false,因为您的模式不包括换行符.

The way I read this "StackOverflow\n".matches("StackOverflow\\z") should return false because your pattern does not include the newline.

"StackOverflow\n".matches("StackOverflow\\z\\n") => false
"StackOverflow\n".matches("StackOverflow\\Z\\n") => true

这篇关于正则表达式中的\ z和\ Z之间有什么区别?何时以及如何使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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