我使用以下表达式:
"?:(.*);GRAYSCALE=([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])(?:;\\w*)?"
1. Input: GRAYSCALE=(120) --> Expected output: true
2. Input: GRAYSCALE=(120); --> Expected output: true
3. Input: GRAYSCALE=(120);abcd --> Expected output: true
4. Input: GRAYSCALE=(120)abcd --> Expected output: false
5. Input: abGRAYSCALE=(120); --> Expected output: false
6. Input: abc;GRAYSCALE=(120);acx --> Expected output: true
对于案例1
- 4
我得到了正确的输出,但不是5
和6
。
答案 0 :(得分:4)
为什么一个正则表达式?使用几个工具:
private static final Pattern SEMICOLON = Pattern.compile(";");
private static final Pattern GRAYSCALE
= Pattern.compile("GRAYSCALE=\\((\\d+\\))");
// Test...
final String[] splits = SEMICOLON.split(input);
Matcher matcher;
boolean found = false;
String inParens;
int number;
for (final String candidate: splits) {
matcher = GRAYSCALE.matcher(candidate);
if (!matcher.find())
continue;
inParens = matcher.group(1);
try {
number = Integer.parseInt(inParens);
break;
} catch (NumberFormatException e) {
// overflow
continue;
}
}
// test "number" here
如果你使用Java 8,这里有一些lambda滥用(上面定义了SEMICOLON
和GRAYSCALE
):
final Optional<String> opt = SEMICOLON.splitAsStream().map(GRAYSCALE::matcher)
.filter(Matcher::find).map(m -> m.group(1)).findFirst();
if (!opt.isPresent()) {
// no luck
}
try {
Integer.parseInt(opt.get());
// Found at least an integer
} catch (NumberFormatException e) {
// overflow
}
答案 1 :(得分:2)
在开头添加单词边界,并将第一个;
作为可选项。此外,您还必须添加模式以匹配()
开括号和右括号。
(.*?)\\b;?GRAYSCALE=\\(([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\)(?:;\\w*)?$
String[] inputs = {
"GRAYSCALE=(120)",// -- Expected output: True
"GRAYSCALE=(120);",// -- Expected output: True
"GRAYSCALE=(120);abcd",// -- Expected output: True
"GRAYSCALE=(120)abcd",// -- Expected output: False
"abGRAYSCALE=(120)",// -- Expected output: False
"abc;GRAYSCALE=(120);acx" // --> Expected output: true
};
Pattern p = Pattern.compile("(.*?)\\b;?GRAYSCALE=\\(([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\)(?:;\\w*)?$");
for (String input: inputs) {
Matcher m = p.matcher(input);
System.out.printf("%s found? %b%n", input, m.find());
}
<强>输出:强>
GRAYSCALE=(120) found? true
GRAYSCALE=(120); found? true
GRAYSCALE=(120);abcd found? true
GRAYSCALE=(120)abcd found? false
abGRAYSCALE=(120) found? false
abc;GRAYSCALE=(120);acx found? true