Negative look ahead java

I need an expression to write a line like this:

"A" [A string that is NOT less than 5 and not more than 6 digits] "B", in other words, captures everything that is NOT the following:

A[0-9][0-9][0-9][0-9][0-9]B
A[0-9][0-9][0-9][0-9][0-9][0-9]B

I tried a negative look ahead

regex = "a((?![0-9]{5,6}).)*d" ;

But he can not display all the scenarios.

+4
source share
4 answers
 A(?!\d{5,6}B).*B 

You want to view only once, right after A And you must include B in the lookahead so that it does not reject anything with more than six digits.

+6
source

These are just a few lines of very simple, understandable and reliable code that you could write and rewrite 3 times in the time it takes for you to publish and get an answer to the RE version. (And, of course, with the RE version it will not be obvious what you are doing).

 int examine(String s) { int foundAt=-1; for(int i=0;i<s.length;i++) { char c=s.charAt(i); // something like that if(c=='A') { foundAt=i; continue; } if(foundAt != -1) { if(c == 'B' && i-foundAt < 5 || i-foundAt > 6) return foundAt; if(!String.isNumber(c)) // something like that foundAt = -1; // Not a number before B, reset } } return -1; } 

Ok, so this is somewhat larger than a few lines (but it is also wrapped in a function call), but changing the behavior to do something complicated is more straightforward than changing the RE, where changes can easily have unintended consequences, it should be it is trivial to read, and once the first few simple mistakes are eliminated, it will be reliable - something that seems to never be true for regular expressions.

So, isn't that as short and readable as you are going to get?

 n=examine(s); 

Any โ€œadvantageโ€ of the shorter code is completely eliminated if it is replaced by a simple and reliable function call.

(I believe that there is a good chance, this is a question of homework, and it should NOT answer it correctly if it exists)

+4
source

You almost have it. Try instead:

 "A(?![0-9]{5,6}B).*B" 

Please note that ".*" Will correspond to greed; if there are several occurrences of B , the match ends last, not first. Instead, you can use ".*?" . For example, if you have a long string with several occurrences of this pattern, and you use the find() method to scan the input string, you would like it to be reluctant to match.

+3
source

Is this a home issue?

I'm not sure why you have "a" and "d" in your regex.

This will handle everything from 0 to 4 digits and 7 or more digits.

 String rexexp = "A(\\d{0,4}|\\d{7,})B"; 
+1
source

Source: https://habr.com/ru/post/1310149/


All Articles