Regex to find 5 consecutive letters of alphabet (ex. abcde, noprst)

Viewed 262

I have strings containing 5 letters of alphabet. I would like to match those that contain letters that are consecutive in alphabet for example:

abcde - return match

nopqrs - return match

cdefg - return match

fghij - return match

but

abcef - do not return match

abbcd - do not return match

I could write all combinations but as you can write in Regex [A-Z] I assumed there must be a better way.

4 Answers

A very simple alternative would be to just use String.prototype.includes:

function isConsecutive(string) {
  const result = 'abcdefghijklmnopqrstuvwxyz'.includes(string);
  console.log(string, result);
}

// true
isConsecutive('abcde');
isConsecutive('nopqrs');
isConsecutive('cdefg');
isConsecutive('fghij');
// false
isConsecutive('abcef');
isConsecutive('abbcd');

If you can live with Python, this function converts the string sequence into numbered characters, and checks if they are consequtive (if so, they are also consecutive alphabetically):

def are_letters_consequtive(text):
    nums = [ord(letter) for letter in text]
    if sorted(nums) == list(range(min(nums), max(nums)+1)):
        return "match"
    return "no match"


print(are_letters_consequtive('abcde'))
print(are_letters_consequtive('cdefg'))
print(are_letters_consequtive('fghij'))

print(are_letters_consequtive('abcef'))
print(are_letters_consequtive('abbcd'))
print(are_letters_consequtive('noprst'))

Outputs:

match
match
match
no match
no match
no match

An alternative using javascript:

let string1 = 'abcde'
let string2 = 'fghiz'


function conletters(string) {
  if(string.length > 5 || typeof string != 'string') throw '[ERROR] not string or string greater than 5'
  for(let i = 0; i < string.length - 1; i++) {
    if(!(string.charCodeAt(i) + 1 == string.charCodeAt(i + 1)))
      return false
  }
  return true
}


console.log('string1 is consecutive: ' + conletters(string1))
console.log('string2 is consecutive: ' + conletters(string2))

You should definitely do it with code:

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

That said, you can do better than testing all the combinations when using regexes. With lookahead expressions you can basically do "and" operation. Since you know the length you could do:

const myRegex = /(?=^(ab|bc)...$)(?=^.(ab|bc)..$)(?=^..(ab|bc).$)(?=^...(ab|bc)$)/

You will need to replace the (ab|bc) with all the possible two combinations.

For this particular case it is actually worse than testing all the possibilities (since there are only 22 possibilities) but it makes it more extensible to other situations.

Related