Java模式接受带空格的字符串

时间:2019-06-05 14:37:02

标签: java regex pattern-matching

我正在尝试使用模式和匹配器在关键字之前和之后的字符串。我目前有此代码

Pattern p = Pattern.compile("([\\w.]+)\\W+=\\W+([\\w.]+)");
        Matcher m = p.matcher("something = 1.21 and another = 2 && something else == 123?");
        while (m.find())
            System.out.printf("'%s', '%s'%n", m.group(1), m.group(2));

输出:

'something', '1.21'
'another', '2'
'else', '123'

我试图只传递“ =”,而不是仅传递“ =“,因为我不想将“ ==”出现在列表中。

无论何时尝试,都不会打印任何内容。

所需的输出:

'something', '1.21'
'another', '2'

1 个答案:

答案 0 :(得分:2)

我认为您当前模式的问题是\W+匹配空格任何其他非单词字符,包括=。这导致==项的错误匹配。我建议仅使用\s*来表示变量名称/值和符号之间的分隔符。这是您脚本的稍微更新的版本:

Pattern p = Pattern.compile("([\\w.]+)\\s*=\\s+([\\w.]+)");
Matcher m = p.matcher("something = 1.21 and another = 2 && something else == 123?");
while (m.find()) {
    System.out.printf("'%s', '%s'%n", m.group(1), m.group(2));
}

这将输出:

'something', '1.21'
'another', '2'