java - 使用 Java 字符串数组设置键值对
问题描述
无法记住这里的状态。感谢任何帮助。我有一个由最终用户设置的字符串,没有验证并且是开放文本。我需要接受它并设置键值对。我忽略了所有其他行(例如:以 : 或 ! 开头)我知道键将以破折号开头(例如:-filePickupDir),然后该值将在下一个空格之后或在下一个带有换行符的空格之后. 如果有续斜线(),那么我知道还有另一个键值对。一些关于用户如何将其落实到位的示例:
-filePickupDir /export/home/PickupDir/\
或者
-filePickupDir \
/export/home/AdjPickupDir/\
示例代码:
HashMap<String, String> processMap = new HashMap<>();
String jobProcess = job.getProcess(); //this is a method that gets the string
String lines[] = jobProcess.split("[\\r\\n]+");
int varCount = 0;
for (String s: lines) {
String key = "";
String val = "";
int count = 0;
int count2 = 0;
if (s.startsWith("!")) {
} else if (s.startsWith(":")) {
} else if (s.startsWith("-")) {
count = s.length() - s.replace(" ", "").length();
count2 = s.length() - s.replace("\\", "").length();
System.out.println("Line space count: " + count + " continue line count: " + count2);
if (count == 1 && count2 == 0 || count == 3 && count2 == 1 || count == 1 && count2 == 1) {
s = s.trim();
int keyIndex = s.indexOf("-");
keyIndex = +1;
int firstSpaceIndex = s.indexOf(" ");
int spaceAfterFirstSpaceIndex = firstSpaceIndex + 1;
int lastIndex = s.length();
String keyString = s.substring(keyIndex, firstSpaceIndex);
String valueString = s.substring(spaceAfterFirstSpaceIndex, lastIndex);
if (count == 3 && count2 == 1) {
int removeSlashIndex = valueString.length();
valueString = valueString.substring(1, removeSlashIndex - 3);
}
} else if (count == 1 && count2 == 1) {
//value is on the next line
//We need to let the program know we have a key but no value and need to maintain state
}
//String split = String.valueOf(s.split("^-(\\w|\\d|\\s)+"));
//System.out.println("split is: "+split.toString());
} else {
//This is value if the key is on its own line above
s = s.trim();
System.out.println("Value: " + s);
}
}
我无法在这里保持状态。我基本上只需要一个以斜杠 (-) 开头的键,然后值是由空格或空格和换行符分隔的下一个字符串。继续处理,直到找到所有密钥对。
要使用的示例字符串数组:
-hostIds \
9\
-最大记录\
1000 \
-xsl\
$batchslx/ziproot/EmailXsl
解决方案
我建议使用正则表达式来做到这一点。您可以像这样捕获第一个示例:
String firstTest = "-filePickupDir /export/home/PickupDir/ \\";
//the capture groups are in the parantheses
String patternString = "[\\n\\s]?-(\\w+)(.+)\\\\";
Pattern pat = Pattern.compile(patternString);
Matcher match = pat.matcher(firstTest);
match.find();
System.out.println(match.group(0)); //whole String
System.out.println(match.group(1)); //first capture group
System.out.println(match.group(2)); //second capture group
//results:
//0 -filePickupDir /export/home/PickupDir/ \
//1 filePickupDir
//2 /export/home/PickupDir/
如果您进一步扩展正则表达式,您将能够完全按照您的描述进行捕获。
推荐阅读
- react-native - 编辑未在 react-native 中填充的屏幕字段
- java - 如何从 Matcher 获取视图
- javascript - 最大素数函数工作太慢
- geojson - Mapbox GL JS:带有外部 JSON 的弹出 onclick
- android - 我们如何在 UI 线程中创建处理程序以将数据发送到另一个线程
- c# - HttpWebRequest 请求被中止:操作已超时
- google-apps-script - 在 Google 脚本中将 HTML 转换为纯文本
- python - Pandas to PySpark:将一列元组列表转换为每个元组项的单独列
- java - 使用抽象参数调用 Java 泛型接口
- javascript - 如何从 javascript 在 div 中插入元素?