-2

I am able to read the content from file

(abcd, 01)
(xyz,AB)
(pqrst, 1E)

And I want to save this content to map as

Map<String, String> map=new HashMap<>();
map.put("abcd","01");
map.put("xyz","AB");
map.put("pqrst","1E");

Help me to get the content as Map using regex in java

Sergei Rybalkin
  • 3,337
  • 1
  • 14
  • 27
Krishna
  • 3
  • 3

3 Answers3

0

I assume you can read each line with a BufferedReader.readLine() or similar. Call that String line. Then to drop the brackets:

line = line.substring(1,line.length()-1);

Then all you want is a split:

String[] bits = line.split(",");
map.put(bits[0], bits[1]);
Manish Patel
  • 4,411
  • 4
  • 25
  • 48
0

The question is about using regexp, but assuming this is not a class assignment etc the solution doesn't require a regexp. A short solution that also handles multiple values per key:

Map<String, List<String>> map = Files.lines(Paths.get("data.txt")).map(s -> s.replace("(", "").replace(")", ""))
                .collect(groupingBy(s -> (s.split(","))[0], mapping(s -> (s.split(",", -1))[1].trim(), toList())));

System.out.println(map);

Will print the resulting map as:

{xyz=[AB], pqrst=[1E], abcd=[01]}

Explanation:

Files.lines(...) //reads all lines from file as a java 8 stream
map(s-> s.replace) // removes all parenthesis from each line
collect(groupingBy(s -> (s.split(","))[0] //collect all elements from the stream and group them by they first part before the ","
mapping(mapping(s -> (s.split(",", -1))[1].trim(), toList()) //and the part after the "," should be trimmed, -1 makes it able to handle empty strings, collect those into a list as the value of the previously grouping

Alternate replace, instead of two simple replace to remove ( and ) you can use

s.replaceAll("\\(|\\)", "")

Not sure which is most readable.

Mattias Isegran Bergander
  • 11,811
  • 2
  • 41
  • 49
0
Pattern pattern = Pattern.compile("^\\(([a-z]+), ([0-9A-Z]+)\\)$");
Map<String, String> map = Files.lines(path)
    .map(pattern::matcher)
    .collect(toMap(x -> x.group(1), x -> x.group(2)));

Match group one is [a-z]+ - key. Match group two is [0-9A-Z]+ - value. Change group patterns on your needs.

Note: regex is a powerful mechanism. If or, to say correctly, when your input data get complex - your pattern will grow and become inapprehensible.

Sergei Rybalkin
  • 3,337
  • 1
  • 14
  • 27