Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if a string has four consecutive letters in ascending or descending order

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.

like image 964
Oneb Avatar asked Dec 07 '22 12:12

Oneb


2 Answers

The answer is simple: don't use regexes.

Use this approach:

  • iterate over each letter (of course, skip the last tree letters)
    • iterate over the next three letters and check for ascending order
      • if they all were ascending return true.
    • iterate over the next three letters and check for descending order
      • if they all were descending return false.
  • return false

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 :)

like image 199
Martijn Courteaux Avatar answered Dec 09 '22 02:12

Martijn Courteaux


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

like image 31
MirrorMirror Avatar answered Dec 09 '22 02:12

MirrorMirror