3
String input0 = "G1 and G2 are the founders of Microsoft.";
String input1 = "The swimming medals were won by G1 and G2";

I would like to parse the above strings and create 2 separate arrays (Note: G1, G2, G3, ... are placeholders for user input and would like to get them separately)

e.g. for input0 the following arrays should be created array0 [G1, G2] and array1 [" and ", " is the founder of Microsoft."]
e.g for input1 the following arrays should be created array0 [G1, G2] and array1 ["The swimming medals were won by ", " and "]

I've tried using indexOf functions and split, but haven't been able to get it working properly so far.

Jason
  • 12,229
  • 20
  • 51
  • 66
  • A regexp is the easiest way to grab g1 and g2 no matter how you represent the data. – Byron Whitlock Dec 22 '10 at 07:26
  • curious to know what is the real usecase for this! – Aravind Yarram Dec 22 '10 at 07:31
  • @Pangea I am looking for users to provide inputs at the locations marked with keywords G1, G2, ... so that I can show this with input text boxes in the user interface. My intention is to find out how many dynamic inputs are needed and will add the rest of the string while rendering either before or after these text boxes. – Jason Dec 22 '10 at 07:33
  • 1
    http://stackoverflow.com/questions/237061/using-regular-expressions-to-extract-a-value-in-java – stacker Dec 22 '10 at 07:34

2 Answers2

4

Take a look at the .split method. You can pass in a regular expression as well. So basically, I am assuming that you know the values of G1 and G2 before hand. So, you do something like this: .split("G1|G2"), replacing G1 and G2 with your strings. You can then use the indexOf method to populate the first array. So you create an ArrayList, use the indexOf method to look for G1 and G2, and if they exist, you add them to the array list. You then use the .split method to populate the second array.

npinti
  • 51,780
  • 5
  • 72
  • 96
1

Use split this way it will separate the second array

String[] result = input0.split("G[0-9]");

And for getting G1, G2, G3 values you can use indexOf() function

niksvp
  • 5,545
  • 2
  • 24
  • 41