Jammy Jammy - 6 months ago 11
Java Question

How to extract specific text from string using Regex in JAVA

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)

Answer

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.