2

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.

M.J.
  • 16,266
  • 28
  • 75
  • 97

2 Answers2

6

Exactly 7 characters

"^[ABCDEFG]{7}$"

1 to 7 characters

"^[ABCDEFG]{1,7}$"
YOU
  • 120,166
  • 34
  • 186
  • 219
  • (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 May 17 '10 at 13:53
  • Adding to the above problem, if i need that one character should come only once, then what will be the expression???? please help.. – M.J. May 17 '10 at 14:01
  • if i need duplicates in the string.. i tried the above one but it is not working.. please help – M.J. May 17 '10 at 14:08
  • @Mrityunjay, Please take a look Tim's comment for that, and Thanks Tim – YOU May 17 '10 at 14:13
  • Probably `"^(?:A()|B()|C()|D()|E()|F()|G()){7}\\1\\2\\3\\4\\5\\6\\7$"` in java, for once char once – YOU May 17 '10 at 14:16
4

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
  • 376,812
  • 128
  • 561
  • 623
  • +1, very nice. still, that uniqueness syntax...that has to be memorized. – Carl May 17 '10 at 15:42
  • @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 May 17 '10 at 15:50