我必须解析具有键值对的属性文件,并且某些行可能会被注释(!或 # ,两者都是有效的)。
例:
key1 val1
Key2 val2
#key3 val3
# key4 val4
# It does not have = symbol
# Spaces can be any where.
...
如果没有注释行,则将键和值读取为匹配器的组值。我使用了以下 RegEx 和代码片段,但它没有按预期捕获键和值:
String inputs[] = {
"key1 val1",
"Key2 val2",
"#key3 val3",
" # key4 val4"
};
Pattern PATTERN = Pattern.compile("^(\\s*[^#!]\\s*)(\\w*)\\s+(\\w*).*$");
for (int i = 0; i < inputs.length; i++) {
System.out.println("Input: " + inputs[i]);
Matcher matcher = PATTERN.matcher(inputs[i]);
if(matcher.matches()) {
int groupCount = matcher.groupCount();
if(groupCount > 0) {
for (int j = 1; j <= groupCount; j++) {
System.out.println(j + " " + matcher.group(j));
}
} else {
System.out.println(matcher.group());
}
} else {
System.out.println("No match found.");
}
System.out.println("");
}
这是输出:
Input: key1 val1
1 k
2 ey1
3 val1
Input: Key2 val2
1 K
2 ey2
3 val2
Input: #key3 val3
No match found.
Input: # key4 val4
No match found.
我的想法是:
^ - Start of line
(\\s*[^#!]\\s*) - space(s) followed by NO # or ! followed by space(s)
(\\w*) - Key
\\s+ - spaces(s)
(\\w*) - Value
.* - Anything
$ - End of line
请帮助我了解这里出了什么问题。为什么它将键的第一个字符作为一个组捕获?