2

I'm writing a parser, where it reads all lines in a particular file and processes it!! I got stuck with this substring Abc [123] where ABC should be stored at as one string, and 123 as other string.so i came up with this solution

lines.get(i).substring(0,lines.get(i).lastIndexOf("["))

this get me the string abc

lines.get(i).substring(lines.get(i).lastIndexOf("["));

and aboveone gets me the string 123] but i dont want ] at last any updation can i make for my approach?

My-Name-Is
  • 4,814
  • 10
  • 44
  • 84
Sai
  • 225
  • 3
  • 15

2 Answers2

1

Change

lines.get(i).substring(lines.get(i).lastIndexOf("["));

to

lines.get(i).substring(lines.get(i).lastIndexOf("[") + 1,lines.get(i).lastIndexOf("]"));
Eran
  • 387,369
  • 54
  • 702
  • 768
0

What about using a regular expression in combination with groups?

Pattern pattern = Pattern.compile("([A-Za-z ]{1,})([\[]{1})([0-9]{1,})");
for(String line : lines){
  Matcher matcher = pattern.matcher(line);
  while (matcher.find()) {
    System.out.println("group 1: " + matcher.group(1));
    System.out.println("group 3: " + matcher.group(3));
  }
}
My-Name-Is
  • 4,814
  • 10
  • 44
  • 84