在Java中使用正则表达式 [英] using regular expression in 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 $ c的排列$ c>,使用否定前瞻和捕获组很容易执行没有重复:
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屋!