我正在尝试在字符串上应用正则表达式以获得以下格式的输出。
输入字符串:
params=Param1{index}~[Value1|Value2|....]^Param2~[Value1|Value2|....]
输出应采用Map<String,List<String>>
的形式
例如。
Key1: Param1
Value : Value1,Value2 upto ValueN
Key2 :Param2
Value: Value1,Value2 uptoValueN
代码: 她是我要做的代码。
String textPatt = "params";
String key = textPatt.replace("/[\\[]/", "\\[").replace("/[\\]]/", "\\]");
String pattern = new String("[\\?&]" + key + "=([^&#]*)");
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(masterUrl);
List<String> paramList = new ArrayList<String>();
if (m.find()) {
String param = m.group();
if(param != null){
String[] multiParamArr = null;
if(param.indexOf("^") != -1){
multiParamArr = param.split("\\^");
}else{
multiParamArr = new String[1];
multiParamArr[0] = param;
}
if(multiParamArr != null && multiParamArr .length > 0){
Pattern refinePattern = null;
Matcher refineMatcher = null;
String paramKeyy = null;
String paramVal = null;
HashMap<String,List<String>> ParamMap = new HashMap<String,List<String>>();
List<String list = new ArrayList<String>();
for(int i=0;i<multiParamArr.length;i++){
String[] multiParam = null;
String patternKey = "^[^\\~]*";
refinePattern = Pattern.compile(patternKey);
refineMatcher = refinePattern.matcher(multiRefineArr[i]);
if(refineMatcher.find()){
paramKey = refineMatcher.group();
if(paramKey.indexOf("=") !=-1){
patternKey = patternKey.substring(patternKey.indexOf("=")+1);
}
if(paramKey.indexOf("{") !=-1){
patternKey = patternKey.substring(patternKey.indexOf("=")+1,patternKey.indexOf("{"));
}
}
if(multiParamArr[i].indexOf("|") != -1){
multiParam = multiParamArr[i].split("\\|");
int startIndex;
int endIndex;
for(int j=0;j<multiParam.length;j++){
startIndex = 0;
endIndex = 0;
ifmultiParamArr[j].indexOf("[") > -1){
startIndex = multiParamArr[j].indexOf("[")+1;
}
ifmultiParamArr[j].indexOf("]") > -1){
endIndex = multiParamArr[j].indexOf("]");
}else{
endIndex = multiParamArr[j].length();
}
paramVal = multiParamArr[j].substring(startIndex,endIndex);
}
}else{
paramVal = multiParamArr[i].substring(multiParamArr[i].indexOfmultiParamArr[i].indexOf("]"));
}
list.add(paramVal);
}
paramMap.put((paramKey,list);
}
}
} 如何应用单个正则表达式并实现输出
答案 0 :(得分:0)
而不是尝试创建复杂的正则表达式并维护它,您可以通过几个步骤更简单,更易读:
^
~
上的每个字符串 - 您将获得一个包含两个字符串的数组,从第一个字符串中提取Param1
(Param2
等)|
(管道)。