如果字符串应包含';',则匹配RegEx在特定字符串之前和之后

时间:2014-12-19 09:47:58

标签: java regex

我使用以下表达式:

"?:(.*);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我得到了正确的输出,但不是56

2 个答案:

答案 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滥用(上面定义了SEMICOLONGRAYSCALE):

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*)?$

DEMO

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

DEMO