在Java中使用正则表达式 [英] using regular expression in Java

查看:104
本文介绍了在Java中使用正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查一个字符串,该字符串应该只包含ABCDEFG字符,任何顺序且只有7个字符。请让我知道使用正则表达式的正确方法。

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.

正如我正在使用

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

我正在使用以下代码,当我使用String abcdefg时,但是对于其他情况,它会失败。请帮帮我。

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

推荐答案

查看字符串是否为 ABCDEFG ,使用否定前瞻和捕获组很容易执行没有重复:

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}$

如果你不需要锚点在Java中使用 String.matches()。这是一个测试工具:

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}")
        );
    }

基本上, [AG] {7} ,还有(?!。*(。)。* \ 1)。也就是说,不会重复任何字符。

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

这是断言的测试工具:

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

它的工作方式是尝试匹配。 *(。)。* \ 1 ,即在。* 之间,捕获的字符(。 )再次出现 \1

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

  • regular-expressions.info/Lookarounds

这篇关于在Java中使用正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆