简体   繁体   中英

using regular expression in Java

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.

Exactly 7 characters

"^[ABCDEFG]{7}$"

1 to 7 characters

"^[ABCDEFG]{1,7}$"

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, [AG]{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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM