英文:
Java Regex match exact SSN pattern
问题
我想从输入字符串中捕获精确的SSN模式DDD-DD-DDDD,而不是其他模式DDD-DD-DDDD-DDD
String line = " Hello my SSN : 111-22-3333-444 and another SSN: 333-56-3789" ;
Pattern p = Pattern.compile("\\b\\d{3}-\\d{2}-\\d{4}\\b");
Matcher m = p.matcher(line);
while(m.find()) {
System.out.println(m.group() );
}
我的输出结果是:
333-56-3789
期望的输出结果:333-56-3789
我尝试添加了\b
边界,但仍然没有成功。
英文:
I want to capture exact SSN pattern DDD-DD-DDDD from the input string not the other pattern DDD-DD-DDDD-DDD
String line = " Hello my SSN : 111-22-3333-444 and another SSN: 333-56-3789" ;
Pattern p = Pattern.compile("\\d{3}-\\d{2}-\\d{4}");
Matcher m = p.matcher(line);
while(m.find()) {
System.out.println(m.group() );
}
I'm getting output as
111-22-3333
333-56-3789
Expected Output: 333-56-3789
I tried adding \b
boundaries still no luck
答案1
得分: 1
你可以使用以下正则表达式:
(?<!\d|\d[.-])\d{3}(?=([.-]))\d{2}\d{4}(?![.-]?\d)
查看 正则表达式演示。详细信息:
(?<!\d|\d[.-])
- 左侧不允许紧邻数字或数字+-
/.
。\d{3}
- 三位数字。(?=([.-]))
- 正向先行断言,捕获下一个字符,必须是.
或-
。\1
- 与前瞻中的捕获组捕获的相同值。\d{2}
- 两位数字。\1
- 与前瞻中的捕获组捕获的相同值。\d{4}
- 四位数字。(?![.-]?\d)
- 右侧不允许紧邻-
/.
+ 数字或仅数字。
查看 Java 演示:
String line = "Hello my 1st SSN : 11.333.56.3788 , 2nd SSN: 333-56-3789 , 3rd SSN 333.56.3780";
Pattern p = Pattern.compile("(?<!\\d|\\d[.-])\\d{3}(?=([.-]))\\\d{2}\\\d{4}(?![.-]?\\d)");
Matcher m = p.matcher(line);
while(m.find()) {
System.out.println(m.group());
}
// => 333-56-3789 and 333.56.3780
英文:
You can use
(?<!\d|\d[.-])\d{3}(?=([.-]))\d{2}\d{4}(?![.-]?\d)
See the regex demo. Details:
(?<!\d|\d[.-])
- no digit nor digit +-
/.
immediately to the left is allowed\d{3}
- three digits(?=([.-]))
- a positive lookahead that captures the next char that must be.
or-
\1
- same value as captured with the capturing group in the lookahead\d{2}
- two diigits\1
- same value as captured with the capturing group in the lookahead\d{4}
- four digits(?![.-]?\d)
- no-
/.
+ digit or just digit is allowed immediately to the right of the current location.
See the Java demo:
String line = "Hello my 1st SSN : 11.333.56.3788 , 2nd SSN: 333-56-3789 , 3rd SSN 333.56.3780" ;
Pattern p = Pattern.compile("(?<!\\d|\\d[.-])\\d{3}(?=([.-]))\\\d{2}\\\d{4}(?![.-]?\\d)");
Matcher m = p.matcher(line);
while(m.find()) {
System.out.println(m.group() );
}
// => 333-56-3789 and 333.56.3780
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论