Home > Mobile >  Regex for recognizing strings consisting of unique characters
Regex for recognizing strings consisting of unique characters

Time:06-17

Could regular expression check if string consist of different letters in case of given string length and any string length ? Aahdj #wrong Gdhjd #wrong Sdfgh #correct Iophdr #correct

CodePudding user response:

For a given length it is possible. You'd make each captured character a capture group, and require that the captured character does not occur ahead. Let's say the length is 4, then:

^([a-z])(?!.*\1)([a-z])(?!.*\2)([a-z])(?!.*\3)([a-z])(?!.*\4)$

If the length is a dynamic input, then the regular expression has to be built dynamically, using some programming language. But the logic is simple.

For instance in JavaScript:

function createRegex(length) {
    let regexString = "^";
    for (let i = 1; i <= length; i  ) {
        regexString  = "([a-z])(?!.*\\"   i   ")"
    }
    regexString  = "$";
    // Create regular expression from string
    return new RegExp(regexString, "i");
}

// Dynamically create the regular expression for a given length
let regex = createRegex(10);
// Print the regular expression
console.log(regex.source);
// Test it on a positive case
console.log(regex.test("abcdefghij")); // true
// and on a negative case
console.log(regex.test("abcDefgDij")); // false

Or in Python:

import re

def createRegex(length):
        regexString = "^"
        for i in range(1, length   1):
            regexString  = rf"([a-z])(?!.*\{i})"
        regexString  = "$"
        # Create regular expression from string
        return re.compile(regexString, re.I)

# Dynamically create the regular expression for a given length
regex = createRegex(10)
# Print the regular expression
print(regex.pattern)
# Test it on a positive case
print(regex.search("abcdefghij"))  # Match object
# and on a negative case
print(regex.search("abcDefDhij"))  # None
  • Related