2016-08-26 11 views
-2

を使用してマッピングするためのファイルから文字列を、私は内容を読み取ることができていたファイルから保存「(キー、値)」Javaの正規表現

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

そして私は

Map<String, String> map=new HashMap<>(); 
map.put("abcd","01"); 
map.put("xyz","AB"); 
map.put("pqrst","1E"); 
として mapにこのコンテンツを保存したいです

私はあなたがBufferedReader.readLine()または類似で各ラインを読むことができると仮定したJava

+3

投稿した内容を投稿してください。 –

+0

http://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java、http://stackoverflow.com/questions/2088037/trim-characters-in-java canを参照してください。ここで助けてください。 –

+0

Javaのどのバージョンを使用しますか?流れはファイルから読んで、マップの権利を保存していますか? –

答えて

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))); 

一致グループ1は[a-z]+ - キーです。 グループ2に一致する値は[0-9A-Z]+ - 値です。 必要に応じてグループパターンを変更します。

注::regexは強力なメカニズムです。入力データが複雑になった場合、正しく言えば、あなたのパターンは大きくなり、理解できなくなります。

+0

ありがとう私はそれを得た – Krishna

0

で私は正規表現を使用して地図などのコンテンツを取得するのに役立ちます。その文字列lineを呼び出します。そして、ブラケットドロップする:

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

を次にあなたが望むすべてが分割さ:

String[] bits = line.split(","); 
map.put(bits[0], bits[1]); 
0

質問は正規表現を使用しますが、仮定については、これはされていないクラス割り当てなどのソリューションを必要としません。正規表現。また、キーごとに複数の値を処理し、短いソリューション:

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); 

は、結果として得られたマップを印刷します:

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

説明:

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 

代替はに置き換える代わりに、2つの単純なの、交換してください削除する(と)使用することができます

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

最も読みやすいものが不明です。

+1

's.replaceAll("^\\(| \\)$ "、" ")'を実行して、大括弧のみを削除する方が良いです。 –