tags:

views:

88

answers:

2

Hi, i need to check a string that should contain only ABCDEFG characters, in any sequence and with only 7 characters. Please let me know the correct way of using regular expression.

as corrently i am using

String abs = "ABPID";
if(!Pattern.matches("[[ABCDEFG]", abs))
System.out.println("Error");

i am using the following code which works when i use the String abcdefg but for other cases it fails. please help me out.

+6  A: 

Exactly 7 characters

"^[ABCDEFG]{7}$"

1 to 7 characters

"^[ABCDEFG]{1,7}$"
S.Mark
(Not quite serious as it's obviously not what the OP meant, but) you can even enforce "exactly 7 characters, no duplicates, in any order": `^(?:A()|B()|C()|D()|E()|F()|G()){7}\1\2\3\4\5\6\7$`
Tim Pietzcker
Adding to the above problem, if i need that one character should come only once, then what will be the expression???? please help..
Mrityunjay
if i need duplicates in the string.. i tried the above one but it is not working.. please help
Mrityunjay
@Mrityunjay, Please take a look Tim's comment for that, and Thanks Tim
S.Mark
Probably `"^(?:A()|B()|C()|D()|E()|F()|G()){7}\\1\\2\\3\\4\\5\\6\\7$"` in java, for once char once
S.Mark
+4  A: 

To see if a string is a permutation of ABCDEFG, it's easy with negative lookahead and capturing group to enforce no duplicates:

^(?!.*(.).*\1)[A-G]{7}$

You don't need the anchors if you use String.matches() in Java. Here's a test harness:

    String[] tests = {
        "ABCDEFG", // true
        "GBADFEC", // true
        "ABCADFG", // false
    };
    for (String test : tests) {
        System.out.format("%s %b%n", test,
            test.matches("(?!.*(.).*\\1)[A-G]{7}")
        );
    }

Basically, [A-G]{7}, but also (?!.*(.).*\1). That is, no character is repeated.

Here's a test harness for the assertion to play around with:

    String[] tests = {
        "abcdeb", // "(b)"
        "abcdefg", // "abcdefg"
        "aba", // "(a)"
        "abcdefgxxxhijyyy" // "(y)"
    };
    for (String test : tests) {
        System.out.println(test.replaceAll("(?=.*(.).*\\1).*", "($1)"));
    }

The way it works is by trying to match .*(.).*\1, that is, with .* in between, a captured character (.) that appears again \1.

See also

polygenelubricants
Nice one! +1 [ ](http://///)
S.Mark
+1, very nice. still, that uniqueness syntax...that has to be memorized.
Carl
@Carl: nope, it's very intuitive. You want to capture `(.)`, and use backreferences to see if it appears again `\1`. You want to allow these two occurrences to be separated by `.*`. It's understandable, it doesn't have to be memorized.
polygenelubricants