Reputation: 1338
I´m trying to capture a substring of a line in Java using the pattern and matcher logic. 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. 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.
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
\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
\d{6}(?!990)
and
\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?
Upvotes: 1
Views: 50
Reputation: 3697
I would avoid regexex if I can since they are hard to debug and have worse performance.
If you can use plain java:
num !=null && num.length() == 9 && num.length.endsWith("770")
Upvotes: 0
Reputation: 626870
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{9}
- nine digits(?!\d)
- no digit immediately to the right of the current location is allowed(?<!770)
- no 770
allowed immediately to the left of the current location.Java string literal:
String regex = "(?<!\\d)\\d{9}(?!\\d)(?<!770)";
Upvotes: 2