[英]Best way to select parts certain parts of data in a string that changes in size
我正在寻找一种很好的方法来解析大小变化的字符串中的某些信息部分。
例如,字符串可能是
“id:1234警告:ab up:12.3 down:12.3”
我需要选择id
, alert
, up
和down
的值,所以我最初的想法是substring但是我认为字符串的长度可以改变大小,例如
“id:123456警告:abcd up:12.345 down:12.345”
因此,每次使用子字符串来查看字符3到7可能每次都不起作用,因为它不会捕获所需的所有数据。
选择每个需要的值的聪明方法是什么? 希望我能很好地解释这一点,因为我通常倾向于将人们与我的错误解释混为一谈。 我用Java编程。
基于正则表达式的基本解决方案可能如下所示:
String input = "id:1234 alert:a-b up:12.3 down:12.3";
Matcher matcher = Pattern.compile("(\\S+):(\\S+)").matcher(input);
while (matcher.find()) {
System.out.println(matcher.group(1) + " = " + matcher.group(2));
}
这假设您要查找一个或多个非空白字符,然后是冒号,然后是一个或多个非空白字符。
输出:
id = 1234
alert = a-b
up = 12.3
down = 12.3
您可以简单地使用String.split() ,首先标记空格,然后在键/值分隔符上进行标记(在这种情况下为冒号):
String line = "id:1234 alert:a-b up:12.3 down:12.3";
// first split the line by whitespace
String[] keyValues = line.split("\\s+");
for (String keyValueString : keyValues) {
String[] keyValue = keyValueString.split(":");
// TODO might want to check for bad data, that we have 2 values
System.out.println(String.format("Key: %-10s Value: %-10s", keyValue[0], keyValue[1]));
}
结果:
Key: id Value: 1234
Key: alert Value: a-b
Key: up Value: 12.3
Key: down Value: 12.3
您可以使用String类中的方法.split()
。
看一下这个:
String line = "id:1234 alert:a-b up:12.3 down:12.3";
String []splittedLine = line.split(" ");
for(int i = 0; i <= splittedLine.length;i++){
System.out.println(splittedLine[i]);
}
你在这里做的是在它找到的每个空白字符上分割你的字符串。 这是结果:
编号:1234
提醒:AB
达:12.3
下跌:12.3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.