Good day stack overflow.
I'm a noob in using regex and here is my problem - I need to check a password if it contains 4 consecutive characters. so far what I have just covered is regarding the digits. Here is my regex:
ascending digits - ^.?(?:0123|1234|2345|3456|4567|5678|6789).$
descending digits - ^.?(?:9876|8765|7654|6543|5432|4321|3210).$
This works only for the digits. I know this is already an overkill in regex so I dont want to do it with the letters. It will be waaay too overkill if I do that.
abcdblah //true because of abcd
helobcde //true because of bcde
dcbablah //true beacause of dcba
heloedcb //true because of edcb
Any help would be highly appreciated. Thanks stackoverflow.
The answer is simple: don't use regexes.
Use this approach:
In code, this would look like this (untested code):
public boolean checkForAscendingOrDescendingPart(String txt, int l)
{
for (int i = 0; i <= txt.length() - l; ++i)
{
boolean success = true;
char c = txt.charAt(i);
for (int j = 1; j < l; ++j)
{
if (((char) c + j) != txt.charAt(i + j))
{
success = false;
break;
}
}
if (success) return true;
success = true;
for (int j = 1; j < l; ++j)
{
if (((char) c - j) != txt.charAt(i + j))
{
success = false;
break;
}
}
if (success) return true;
}
return false;
}
Good luck!
StackOverflow :)
here is an idea that doesn't use regex: all characters have an ansi value and usually consecutive. so abcd should have let's say the following ansi values:64,65,66,67
pseudocode:
for (i=string.start;i<string.end-4;i++) {
check=string.substring(i,4);
c1=check.substring(0,1);
c2=check.substring(1,1);
c3=check.substring(2,1);
c4=check.substring(3,1);
if (c1.ansival==c2.ansival+1 && c2.ansival==c3.ansival+1 && c3.ansival==c4.ansival+1) {
return false;
} else {
return true;
}
}
also repeat in reverse order (c1.ansival+1==c2.ansival) for descending order
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With