Jammy
Jammy

Reputation: 71

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)

Upvotes: 1

Views: 773

Answers (3)

Mario Cairone
Mario Cairone

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

Scott Weaver
Scott Weaver

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: "\"((?:\\\\\\\\|\\\\\"|[^\"])+)\""

regex demo

Upvotes: 1

Sanjeev
Sanjeev

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

Related Questions