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)

6
  • 3
    Please add your tried code Commented May 12, 2016 at 17:07
  • That looks like a JSON Array, so a JSON parser would be a good choice. Commented May 12, 2016 at 17:10
  • @Sanjeev added! Thanks. Commented May 12, 2016 at 17:18
  • I ran your code and it is doing what you want Commented May 12, 2016 at 17:41
  • 2
    Using a JSON Parser is the right way to solve this, You can refer stackoverflow.com/questions/8264725/… Commented May 12, 2016 at 17:41

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

It was helpful! Tnx!
no prob. you can go here to convert from a regex to properly escaped java string: regexplanet.com/advanced/java/index.html
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.

1 Comment

Thanks, I corrected a small error in my code. Now it's working.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.