gpt4 book ai didi

java - Java中的正则表达式: Pattern.编译( "J.*\\d[0-35-9]-\\d\\d-\\d\\d")

转载 作者:行者123 更新时间:2023-12-03 02:40:34 26 4
gpt4 key购买 nike

我在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 个数字。

最佳答案

\\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

关于java - Java中的正则表达式: Pattern.编译( "J.*\\d[0-35-9]-\\d\\d-\\d\\d"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19851462/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com