mirchev1977
mirchev1977

Reputation: 167

How to create a regex consisting of specific characters occupying a specific order, but having different length

Let us say we have the word residence. It could be matched by the following regular expression in js:

residence.match( new RegExp(/[residence]{4,9}/, 'i' ) )

This is fine, but there is a problem for me: All the letters are interchangeable. This expression could match also:

ceresiden, denceresid, ence etc...

I would like to have the order of the characters preserved. The regex should match strings like:

resid sidence ience rednce etc..

How can I achieve this? Thanks!

Upvotes: 0

Views: 110

Answers (2)

Toto
Toto

Reputation: 91508

Use lookahead to test the valid strings and then test the length:

var test = [
    'ceresiden',
    'denceresid',
    'ence',
    'res',
    'den',
    'resid',
    'sidence',
    'ience',
    'rednce',
];
console.log(test.map(function (a) {
  return a + ' :' + a.match(/^(?=r?e?s?i?d?e?n?c?e?$).{4,9}$/);
}));

Upvotes: 2

IceMetalPunk
IceMetalPunk

Reputation: 5566

So you want them in the same order, but possibly with any number of characters removed? Then just make each character optional: /(r?e?s?i?d?e?n?c?e?){4,9}/i

Note: this regex, and the one you posted, will not match any of the strings you specified, because of the {4,9} quantifier. A string matching the pattern must including substrings matching the "residence"-optional pattern at least 4 times in a row (without spaces, etc.) for it to match.

Upvotes: 1

Related Questions