我有以下字符串:
mac1: 00:11:22:33:44:55
mac2: 66:77:88:99:00:11
model: PI-504
first_name: any_name
device_type: baseboard
serial_number: 668778542298745210
我想将所有值提取到数组中。如何用Java做到这一点?
public String[] getvaluesIntoStringArray(String str) {
....
}
答案 0 :(得分:2)
您可以使用regular expressions:
private static final Pattern PATTERN = Pattern.compile(".*?:(.*)");
public static String[] getvaluesIntoStringArray(String str) {
Matcher matcher = PATTERN.matcher(str);
List<String> values = new ArrayList<String>();
while (matcher.find())
values.add(matcher.group(1).trim());
return values.toArray(new String[values.size()]);
}
答案 1 :(得分:1)
如果你想拆分新行,那么我认为应该这样做
public String[] getvaluesIntoStringArray(String str) {
return str.split("\\r?\\n");
}
答案 2 :(得分:0)
使用此正则表达式(?<=:\s)(.+$)
如果您的正则表达式引擎不支持lookbehind使用此正则表达式(:\s)(.+$)
匹配将在第2组
p.s。:使用带有正则表达式选项MultyLine
答案 3 :(得分:0)
String str = "mac1: 00:11:22:33:44:55
mac2: 66:77:88:99:00:11
model: PI-504
first_name: any_name
device_type: baseboard
serial_number: 668778542298745210";
String[] tempArr = str.split("\n");
此tempArr应包含值为mac1:00:11:22:33:44:55,mac2:66:77:88:99:00:11,型号:PI-504,first_name:any_name,device_type: baseboard,serial_number:668778542298745210
答案 4 :(得分:0)
请尝试
String[] result = str.split("\n");
答案 5 :(得分:0)
这里代码:
public static void main(String[] args) {
List<String> result = new ArrayList<String>();
String str = "mac1: 00:11:22:33:44:55\n" +
"mac2: 66:77:88:99:00:11\n" +
"model: PI-504\n" +
"first_name: any_name\n" +
"device_type: baseboard\n" +
"serial_number: 668778542298745210";
Pattern pattern = Pattern.compile("^.*?:(.*)$", Pattern.MULTILINE);
Matcher matcher = pattern.matcher(str);
boolean find = matcher.find();
while(find) {
result.add(matcher.group(1));
find = matcher.find();
}
System.out.print(result);
}