正则表达式中的奇怪行为 [英] Strange behavior in regexes

查看:126
本文介绍了正则表达式中的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个关于正则表达式的问题并试图回答我发现了另一个奇怪的事情。

There was a question about regex and trying to answer I found another strange things.

String x = "X";
System.out.println(x.replaceAll("X*", "Y"));

这会打印YY。为什么??

This prints YY. why??

String x = "X";
System.out.println(x.replaceAll("X*?", "Y"));

这打印YXY

为什么不情愿正则表达式与'X'字符不匹配?有注意X没有但为什么第一个不匹配三个符号并匹配两个然后一个而不是三个?和第二个正则表达式只匹配没有 s而不是 X

Why reluctant regex doesn't match 'X' character? There is "noting"X"nothing" but why first doesn't match three symbols and matches two and then one instead of three? and second regex matches only "nothing"s and not X?

推荐答案

让我们依次考虑它们:

"X".replaceAll("X*", "Y")

有两场比赛:


  1. 在字符位置0处, X 匹配,并替换为 Y

  2. 在字符位置1处,匹配空字符串,并将 Y 添加到输出中。

  1. At character position 0, X is matched, and is replaced with Y.
  2. At character position 1, the empty string is matched, and Y gets added to the output.

最终结果: YY

"X".replaceAll("X*?", "Y")

还有两场比赛:


  1. 在字符位置0处,空字符串匹配,并且 Y 被添加到输出中。 此位置的字符 X 未被匹配使用,因此会逐字复制到输出中。

  2. 在字符位置1处,匹配空字符串,并将 Y 添加到输出中。

  1. At character position 0, the empty string is matched, and Y gets added to the output. The character at this position, X, was not consumed by the match, and is therefore copied into the output verbatim.
  2. At character position 1, the empty string is matched, and Y gets added to the output.

最终结果: YXY

这篇关于正则表达式中的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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