使用reg表达式分割字符串

时间:2019-03-07 06:44:04

标签: java android regex

我有一个像element= "a||||b||||c"这样的字符串,我想通过使用

来分割一个[a,b,c]
Pattern pattern=Pattern.compile("\\|\\|\\|\\|")
String[] splitedValues = pattern.split(element);

我有splitedValues =[a,b,c] 3码

如果element=||||||||我得到了splitedValues 尺寸0

我想要 splitedValues =["","",""],且尺寸3

我该如何实现?

2 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情。

     /**
 * @param rgbColor/argbColor This function take "rgb(123,23,23)/argb(123,12,12,12)" as input String and returns
 *                           actual Color object for its equivalent rgb value
 */
public static int parseRgbColor(@NonNull String rgbColor) {
    Pattern rgbColorPattern = Pattern.compile("rgb *\\( *([0-9]+), *([0-9]+), *([0-9]+) *\\)");
    Pattern argbColorPattern = Pattern.compile("argb *\\( *([0-9]+), *([0-9]+), *([0-9]+), *([0-9]+) *\\)");

    Matcher colorMatch = rgbColorPattern.matcher(rgbColor.toLowerCase());
    if (colorMatch.matches()) {
        return Color.rgb(Integer.valueOf(colorMatch.group(1)), Integer.valueOf(colorMatch.group(2)), Integer.valueOf(colorMatch.group(3)));
    } else {
        colorMatch = argbColorPattern.matcher(rgbColor.toLowerCase());
        if (colorMatch.matches()) {
            return Color.argb(Integer.valueOf(colorMatch.group(1)), Integer.valueOf(colorMatch.group(2)), Integer.valueOf(colorMatch.group(3)), Integer.valueOf(colorMatch.group(4)));
        }
    }
    return -1;
}

答案 1 :(得分:0)

您可以使用字符串拆分功能,

public class MySoundPool {

    private static SoundPool soundPool;
    private static int sound;

    public MySoundPool(Context context) {
        AudioAttributes audioAttributes = new AudioAttributes.Builder()
                .setLegacyStreamType(AudioManager.STREAM_MUSIC)
                .build();

        soundPool = new SoundPool.Builder()
                .setMaxStreams(3)
                .setAudioAttributes(audioAttributes)
                .build();
    }
}

输出

      String test = "||||||||";
    String[] testArray = test.split("\\|\\|\\|\\|", -1);
    for (String t : testArray) {
        System.out.println("Data " + t);
    }
    System.out.println("test " + test + " size :" + testArray.length);
    test = "a||||b||||c";
    System.out.println("---------");
    testArray = test.split("\\|\\|\\|\\|", -1);
    for (String t : testArray) {
        System.out.println("Data " + t);
    }
    System.out.println("test " + test + " size :" + testArray.length);