0

I'm scanning through an array of String objects, each string object is going to be broken down into a regex.

When going through a an enhanced for-loop I'm wondering, is it possible to put the retval into an array?

For example if I have String regex = new String[3];

Where regex[0] = "EVEN_BIN_NUM (0|1)*0"

The enhanced for-loop can break my String object up into EVEN_BIN_NUM and (0|1)*0

I want to be able to put EVEN_BIN_NUM in one array, and (0|1)*0 in another array. Here is the code I have that scans through the String array with the string objects

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

For regex[0].split(" ", 2) I get EVEN_BIN_NUM and (0|1)*0 returned separately.

Alternatively, if you know how to break this up in a better way, let me know: EVEN_BIN_NUM (0|1)*0

ODD_BIN_NUM (0|1)*1

PET (cat|dog)

The parts in capital letters are to be put in the "kind" array, and the rest is to be put in another array.

So the kind array would have three strings, and the other array would have three strings.

Hopefully this isn't too confusing....

1
  • You will eventually need someway to identify which element you are looping in the for loop, so just write a normal loop, and assign the return value to the appropriate array. Commented Sep 19, 2014 at 4:05

1 Answer 1

1

It might be a good idea to use a Map object to store your information, however, if you wanted to return your analysis as an array, you could return an array of arrays and do the following.

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

}

You can then access the data as follows

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

etcetera.

Or using a map:

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

}

This way your properties would map straight to your Patterns.

For example:

Pattern petPattern = map.get("PET");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.