我写了一个正则表达式来解析格式的字符串
OBJECT_NAME KEY1=值 KEY2=值
(实际上由 2 个正则表达式完成)
这是我的实用程序类:
package de.hs.settlers.util;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ParseUtils {
public static final Pattern OBJECT_NAME_PATTERN =
Pattern.compile("^([A-Z0-9 ]+) ([A-Z]+=.+)$");
public static final Pattern KEY_VALUE_PATTERN =
Pattern.compile("^([A-Z0-9]+)=([^=]+)( [A-Z]+=.+)?$");
public static ParseResult parseKeyValueLine(String line) {
Matcher object = OBJECT_NAME_PATTERN.matcher(line.trim());
String objectName = object.group(1);
HashMap<String, String> data = new HashMap<String, String>();
String vals = object.group(2);
do {
Matcher matcher = KEY_VALUE_PATTERN.matcher(vals);
if (!matcher.matches()) {
break;
}
String key = matcher.group(1);
String value = matcher.group(2);
data.put(key, value);
vals = matcher.group(3);
if (vals != null) {
vals = vals.trim();
}
} while (vals != null);
return new ParseResult(objectName, data);
}
public static class ParseResult {
private String objectName;
private HashMap<String, String> data;
public ParseResult(String objectName, HashMap<String, String> data) {
super();
this.objectName = objectName;
this.data = data;
}
public String getObjectName() {
return objectName;
}
public HashMap<String, String> getData() {
return data;
}
public String get(String key) {
return getData().get(key);
}
}
}
我编写了一个测试,以“USER TEAM=Team A USER=tuxitux OTHER=bla”作为行参数来测试方法 parseKeyValueLine,但是执行失败,因为第一个表达式(OBJECT_NAME_PATTERN 中的那个)显然不匹配。
我遇到的问题是,当我将表达式和字符串粘贴到正则表达式调试器中时,它们都告诉我它匹配并给我正确的组。(用http://gskinner.com/RegExr/和http://www.debuggex.com/测试)。
java做正则表达式有什么问题吗?