Java正则表达式找到多个模式,需要将其转换为Map

时间:2014-03-22 03:10:23

标签: java regex

我正在尝试使用各种模式从多行String创建地图 例如,考虑以下String

:20:94001142322029214336
:86:/PG/1L
:25|11298666
:28::20/1

我的模式如下:

starting  : OR :: OR | OR || and ending with : OR :: OR | OR ||

我正在尝试按如下方式创建地图:

Key    Value

20    94001142322029214336<br>
86    /PG/1L<br>
25    11298666<br>
28    20/1<br>

您能否帮我创建Java正则表达式或任何其他可以帮助我创建此地图的解决方案?

感谢。

3 个答案:

答案 0 :(得分:0)

您可以尝试使用正则表达式:

:(\w+)[:\|]+(.*)

<强>代码

private static final Pattern REGEX_PATTERN = 
        Pattern.compile(":(\\w+)[:\\|]+(.*)");

public static void main(String[] args) {
    Map<String, String> map = new LinkedHashMap<>();
    String input = ":20:94001142322029214336\n:86:/PG/1L\n:25|11298666\n:28::20/1";
    Matcher matcher = REGEX_PATTERN.matcher(input);
    while (matcher.find()) {
        map.put(matcher.group(1), matcher.group(2));
    }
    for(Map.Entry<String, String> entry : map.entrySet()) {
        System.out.printf("Key=\"%s\", Value=\"%s\"%n", 
                entry.getKey(), entry.getValue());
    }
}

<强>输出

Key="20", Value="94001142322029214336"
Key="86", Value="/PG/1L"
Key="25", Value="11298666"
Key="28", Value="20/1"

答案 1 :(得分:0)

尝试,

String strArray[] = { ":20:94001142322029214336",
                 ":86:/PG/1L" ,
                 ":25||11298666" ,
                 ":28::20/1"
               };
HashMap<String,String>map = new HashMap<String,String>();
for(String str11 : strArray){
    String subStr[] = str11.replaceFirst(":","").split(":{2}|:|\\|{2}|\\|");
    map.put(subStr[0],subStr[1]);
    System.out.println(subStr[0]+"-->"+subStr[1]);
}

输出:

20-->94001142322029214336
86-->/PG/1L
25-->11298666
28-->20/1

正则表达式:{2}|:|\\|{2}|\\|说明:

enter image description here

答案 2 :(得分:0)

试试这个:

public static void main(String[] args) {
    Map<String, String> map = new HashMap<>();
    String s = ":20:94001142322029214336\n:86:/PG/1L\n:25|11298666\n:28::20/1";
    System.out.println("Original string: \n"+s);

    // Transform the string into an array of lines
    String[] lines = s.split("\n");

    for(int i = 0; i < lines.length; i++) {
        // Split using regex - notice that the two-character symbols need to go first
        String[] parts = lines[i].split("::|:|\\|\\||\\|");
        map.put(parts[1], parts[2]);
    }

    System.out.println("\nMap: ");
    for(String key : map.keySet()) {
        System.out.println(key+"->"+map.get(key));
    }
}