简体   繁体   English

Java模式正则表达式,用于查找不以特定子字符串结尾的数字

[英]Java Pattern Regex for finding numbers not ending with specific substring

I´m trying to capture a substring of a line in Java using the pattern and matcher logic. 我正在尝试使用模式和匹配器逻辑捕获Java中一行的子字符串。 For the current application I need to remove a substring of a line. 对于当前应用程序,我需要删除一行的子字符串。 therefore i want to capture the whole substring ending with a number which should not end with a specified 3 digit number reserved for other purposes. 因此,我想捕获整个子字符串,该子字符串的数字不应以为其他目的保留的指定3位数字结尾。 I also can´t simply Strip of a hardcoded amount of characters from my line, therefore a regex is needed. 我也不能简单地从行中剥离一定数量的硬编码字符,因此需要一个正则表达式。 To simplify the Problem, the regex should just capture numbers of 9 digits not ending with 770. 为了简化问题,正则表达式应该只捕获不以770结尾的9位数字。

this should be the results: 这应该是结果:

233456770 --> NO HIT
454683870 --> HIT
459987579 --> HIT

i tried the solution with the following solution, Stripping all numbers ending with a 0 我尝试了以下解决方案,剥离所有以0结尾的数字

\d{6}[^9][^9][^0]

I also tried a lookbehind, which resulted either in the substring beeing too Long or to short since there are 3 digits missing or too much 我还尝试了回溯,这导致子字符串太长或太短,因为缺少3位数字或太多了

\\d{6}(?!990) and \\d{6}(?!990)

\d{9}(?!990)

So how to detect and capture a number not ending with a specified substring while keeping the whole detected number (withoud removing the last three digits checked) in the resulting substring using Java Pattern language? 那么,如何使用Java Pattern语言在结果子字符串中保留检测到的整个数字(不删除最后检查的三位数字)的同时,如何检测和捕获不以指定子字符串结尾的数字?

You may use 您可以使用

(?<!\d)\d{9}(?!\d)(?<!770)

See this demo . 看到这个演示

Details 细节

  • (?<!\\d) - no digit immediately to the left of the current location is allowed (?<!\\d) -当前位置左边不允许有数字
  • \\d{9} - nine digits \\d{9} -九位数
  • (?!\\d) - no digit immediately to the right of the current location is allowed (?!\\d) -当前位置右边不允许有数字
  • (?<!770) - no 770 allowed immediately to the left of the current location. (?<!770) -当前位置左边不允许有770

Java string literal: Java字符串文字:

String regex = "(?<!\\d)\\d{9}(?!\\d)(?<!770)";

I would avoid regexex if I can since they are hard to debug and have worse performance. 如果可以的话,我将避免使用regexex,因为它们很难调试并且性能较差。

If you can use plain java: 如果可以使用纯Java:

num !=null && num.length() == 9 && num.length.endsWith("770")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM