你可以把Java Retval放入一个数组

时间:2014-09-19 03:57:12

标签: java arrays regex string

我正在扫描一个String对象数组,每个字符串对象将被分解为正则表达式。

当我想通过一个增强的for循环时,是否可以将retval放入数组?

例如,如果我有String regex = new String [3];

其中regex [0] =“EVEN_BIN_NUM(0 | 1)* 0”

增强的for循环可以将我的String对象分解为EVEN_BIN_NUM和(0 | 1)* 0

我希望能够将EVEN_BIN_NUM放在一个数组中,将(0 | 1)* 0放在另一个数组中。这是我用字符串对象

扫描String数组的代码
    /*
     * Run through each String object and appropriately place them in the kind,
     * and explicit.
     */
    for (int j = 0; j < regex.length; j++)
    {
        for (String retval: regex[j].split(" ", 2))
        {
            System.out.println(retval);
        }
    }

对于正则表达式[0] .split(“”,2)我得到EVEN_BIN_NUM并且(0 | 1)* 0单独返回。

或者,如果你知道如何以更好的方式解决这个问题,请告诉我: EVEN_BIN_NUM(0 | 1)* 0

ODD_BIN_NUM(0 | 1)* 1

PET(猫|狗)

大写字母的部分将放在“kind”数组中,其余部分放在另一个数组中。

所以kind数组有三个字符串,另一个数组有三个字符串。

希望这不会太混乱......

1 个答案:

答案 0 :(得分:1)

使用Map对象存储信息可能是个好主意,但是,如果要将分析作为数组返回,则可以返回数组数组并执行以下操作。

String[] regex = {"EVEN_BIN_NUM (0|1)*0", "ODD_BIN_NUM (0|1)*1", "PET (cat|dog)"} ;
String[][] split = new String[regex.length][];

for(int i = 0; i < regex.length; i++) {
  split[i] = regex[i].split(" ", 2);

}

然后您可以按如下方式访问数据

String firstProperty = split[0][0];   //EVEN_BIN_NUM
String firstRegex = split[0][1];      //(0|1)*0

String secondProperty = split[1][0];  //ODD_BIN_NUM
String secondRegex = split[1][1];     //(0|1)*1

等等。

或使用地图:

Map<String, Pattern> map = new HashMap<>();

for(int i = 0; i < regex.length; i++) {
  String[] splitLine = regex[i].split(" ", 2);
  map.put(splitLine[0], Pattern.compile(splitLine[1]));

}

这样您的属性就会直接映射到您的模式。

例如:

Pattern petPattern = map.get("PET");
相关问题