0

我有这种格式的字符串

< value1 >,< value2 >, <1,2,3,4,5>,< some value >

输出必须是字符串数组:

array[0] = "value1";
array[1] = "value2";
array[2] = "1,2,3,4,5";
array[3] = "some value";

有什么建议最好的方法是什么?

4

3 回答 3

3

这是如何在一行中完成的:

String[] array = input.replaceAll("(^< *)|( *>$)", "").split(" *>, *< *");
于 2013-06-01T22:53:43.477 回答
3
package com.sandbox;

import org.junit.Test;

import static junit.framework.Assert.assertEquals;

public class SandboxTest {

    @Test
    public void testQuestionInput() {
        String input = "< value1 >,< value2 >, <1,2,3,4,5>,< some value >";
        String [] output = splitter(input);
        assertEquals("value1", output[0]);
        assertEquals("value2", output[1]);
        assertEquals("1,2,3,4,5", output[2]);
        assertEquals("some value", output[3]);
    }

    private String[] splitter(String input) {
        String[] split = input.split(">\\s*,\\s*<");
        for (int i = 0; i < split.length; i++) {
            String s = split[i];
            s = s.replaceAll("<", "");
            s = s.replaceAll(">", "");
            s = s.trim();
            split[i] = s;
        }
        return split;
    }


}
于 2013-06-01T22:27:58.227 回答
3

一点正则表达式魔法怎么样?

public static void main(String[] args) {
    final String myString = "< value1 >,< value2 >, <1,2,3,4,5>,< some value >";
    final Pattern pattern = Pattern.compile("(?<=<)[^>]++(?=>)");
    final Matcher m = pattern.matcher(myString);
    while(m.find()) {
        System.out.println(m.group().trim());
    }
}

输出:

value1
value2
1,2,3,4,5
some value
于 2013-06-01T22:34:34.780 回答