Java正则表达式匹配精确的社会安全号码模式

huangapple go评论62阅读模式
英文:

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

(?&lt;!\d|\d[.-])\d{3}(?=([.-]))\d{2}\d{4}(?![.-]?\d)

See the regex demo. Details:

  • (?&lt;!\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 = &quot;Hello my 1st SSN : 11.333.56.3788 , 2nd SSN: 333-56-3789 , 3rd SSN 333.56.3780&quot; ;
Pattern p = Pattern.compile(&quot;(?&lt;!\\d|\\d[.-])\\d{3}(?=([.-]))\\\d{2}\\\d{4}(?![.-]?\\d)&quot;);
Matcher m = p.matcher(line);
while(m.find()) {
    System.out.println(m.group() );
}
// =&gt; 333-56-3789 and 333.56.3780

huangapple
  • 本文由 发表于 2020年9月25日 18:55:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/64062737.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定