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)
source share