Reputation: 71
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)
Upvotes: 1
Views: 773
Reputation: 1144
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.
Upvotes: 1
Reputation: 7361
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: "\"((?:\\\\\\\\|\\\\\"|[^\"])+)\""
Upvotes: 1
Reputation: 9946
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.
Upvotes: 1