Java中的正则表达式:Pattern.compile(“J。* \\ d [0-35-9] - \\ d \\ d - \\ d \\ d”)

时间:2013-11-08 04:13:24

标签: java regex syntax

我在Java正则表达式中找到了一个令我困惑的代码:

Pattern.compile( "J.*\\d[0-35-9]-\\d\\d-\\d\\d" );

要编译的字符串是:

String string1 = "Jane's Birthday is 05-12-75\n" + "Dave's Birthday is 11-04-68\n" + "John's Birthday is 04-28-73\n" + "Joe's Birthday is 12-17-77";

是什么意思
[0-35-9]

为什么有4个“\ d”而不是3个?我假设生日那天只有3个号码。

4 个答案:

答案 0 :(得分:2)

\\d与数字不匹配,与数字匹配。区别在于\\d\\d将匹配两个连续的数字。

[0-35-9]将匹配0-3范围内的数字或5-9范围内的数字。

实际结果是,这与月份为10,11,12,01,02,03,05,06,07,08或09的生日相匹配。日期和年份无关紧要,只要它们是两位数。这是一种非常啰嗦的说法,“找到一个不是四月的生日(04)”。

答案 1 :(得分:2)

  

[0-35-9]

是什么意思

这意味着您提供方括号内的set of characters。它指定将成功匹配给定输入字符串中的单个字符的给定字符。因此,如果匹配的字符属于03,或59,则上述类字符将匹配。

  

为什么有4个“\ d”而不是3个?我假设只有3个   生日那天的数字。

您的生日字符串部分为:Birthday is 05-12-75

\dpredefined character class,其中\d代表一个数字,\d\d代表两个连续数字。因此,对于约会xx-xx-xx-xx,我们会写\\d\\d-\\d\\d-\\d\\d-\\d\\d,其中假设x代表一个数字(0-9

答案 2 :(得分:2)

\\d的形式只是匹配数字,而不是数字。

因此,使用\\d\\d的模式将匹配两个连续的数字。

使用\\d\\d-\\d\\d将匹配两个连续数字,一个-字面上,两个连续数字。

让我们来看看你的比赛以及原因。

Joe's Birthday is 12-17-77
                  ^          match a digit 0 to 9
                   ^         match any character of '0' to '3', '5' to '9'
                    ^        match a '-' literally
                     ^       match a digit 0 to 9
                      ^      match a digit 0 to 9
                       ^     match a '-' literally
                        ^    match a digit 0 to 9
                         ^   match a digit 0 to 9

[0-35-9]部分匹配0359的所有字符

你的整个普通快报都解释道:

J              'J'
.*              any character except \n (0 or more times)
\d              match a digit 0 to 9
 [0-35-9]       any character of: '0' to '3', '5' to '9'
   -            match a '-' literally
  \d            match a digit 0 to 9
  \d            match a digit 0 to 9 
   -            match a '-' literally
  \d            match a digit 0 to 9
  \d            match a digit 0 to 9

答案 3 :(得分:1)

我们感知数字的方式出现了混乱。对于我们的数学眼睛,它看起来中间部分是单个数字,数字“35”。但实际上,它是两个数字,一个“3”和一个“5”。正如之前已经深入回答的那样,这实际上是两个范围,从0到3(包括0和3)的数字范围,以及从5到9(包括5和9)的范围,从而从它将匹配的可能数字中消除4个。

关于“\ d”的数量,实际上有5个不是4.第一个与数字范围内的单个数字配对以匹配一个月(例如,10月是10月,6月是06,所以两者都匹配,而四月,即04,则不然。接下来的两个“\ d”对成为一天。最后两对结束了一年。