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.

1
  • 1
    How about duplicates? Is "AAAAAAA" also acceptable? Commented May 17, 2010 at 13:39

2 Answers 2

6

Exactly 7 characters

"^[ABCDEFG]{7}$"

1 to 7 characters

"^[ABCDEFG]{1,7}$"
Sign up to request clarification or add additional context in comments.

5 Comments

(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$
Adding to the above problem, if i need that one character should come only once, then what will be the expression???? please help..
if i need duplicates in the string.. i tried the above one but it is not working.. please help
@Mrityunjay, Please take a look Tim's comment for that, and Thanks Tim
Probably "^(?:A()|B()|C()|D()|E()|F()|G()){7}\\1\\2\\3\\4\\5\\6\\7$" in java, for once char once
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

2 Comments

+1, very nice. still, that uniqueness syntax...that has to be memorized.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.