简体   繁体   English

从字符串中提取子字符串

[英]Extract sub-strings from string

I have the following String: 我有以下字符串:

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

And I want to extract all values into an array. 我想将所有值提取到数组中。 How to do it with Java? 用Java怎么做?

public String[] getvaluesIntoStringArray(String str) {
    ....
}

You can use 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()]);
}

If you want to split new lines then I think this should do it 如果您想分割新行,那么我认为应该这样做

public String[] getvaluesIntoStringArray(String str) {
    return str.split("\\r?\\n");
}

use this regex (?<=:\\s)(.+$) if your regex engine does not suppirt lookbehind use this regex (:\\s)(.+$) matches will be in group 2 如果您的正则表达式引擎不支持向后看,请使用此正则表达式(?<=:\\s)(.+$)使用此正则表达式(:\\s)(.+$)将在第2组中进行匹配

ps: use regex with regexoption MultyLine ps:将regex与regexoption MultyLine

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");

this tempArr should contain the values as 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 此tempArr的值应为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[] result = str.split("\n");    

Here code: 这里的代码:

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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM