1

I have a String = '["Id","Lender","Type","Aging","Override"]'

from which I want to extract Id, Lender, Type and so on in an String array. I am trying to extract it using Regex but, the pattern is not removing the "[".

Can someone please guide me. Thanks!

Update: code I tried,

Pattern pattern = Pattern.compile("\"(.+?)\"");
Matcher matcher = pattern.matcher(str);
List<String> list = new ArrayList<String>();
while (matcher.find()) {
// System.out.println(matcher.group(1));.
list.add(matcher.group(1));

(Ps: new to Regex)

Jammy
  • 71
  • 2
  • 14

3 Answers3

1

but if your input was, say:

["Id","Lender","Ty\"pe","Aging","Override", "Override\\\\\"\""]

this regex will capture all values, while allowing those (valid) escaped quotes \" and literal backslashes \\ in your strings

  • regex: "((?:\\\\|\\"|[^"])+)"

  • or as java string: "\"((?:\\\\\\\\|\\\\\"|[^\"])+)\""

regex demo

Scott Weaver
  • 7,192
  • 2
  • 31
  • 43
1

You can do something like this. It first removes "[ ]" and then splits on ","

System.out.println(Arrays.toString(string.replaceAll("\\[(.*)\\]", "$1").split(",")));

Hope this helps.

Sanjeev
  • 9,876
  • 2
  • 22
  • 33
1

Your code works, I tried it and I got the output you want.

String line = "[\"Id\",\"Lender\",\"Type\",\"Aging\",\"Override\"]";

Pattern r = Pattern.compile("\"(.+?)\"");
List<String> result = new ArrayList<>();        
// Now create matcher object.
Matcher m = r.matcher(line);
while (m.find( )) {
      result.add(m.group(1));
 } 
System.out.println(result);

output:

[Id, Lender, Type, Aging, Override]

obviously the square brackets are there because I am printing a List, they are not part of the words.

Blake Yarbrough
  • 2,286
  • 1
  • 20
  • 36
Mario Cairone
  • 1,071
  • 7
  • 11