2016-04-22 15 views
1

私はこのような文字列表現を持っている:文字列式Javaで文字列パターンを見つける方法は?

(code name credits) or ((code name credits) and (code name credits)) 

私は、文字列内のすべての(コード名クレジット)の組み合わせを認識し、その値に置き換えたいです。

コードは、文字と数字の組み合わせです。

名前は、単語の組み合わせで、1つのスペースで区切られ、文字と数字の両方を持つことができます。

クレジットは数字です。

各コンポーネントは、タブで区切られています。

(コードネームクレジット)の実際の例の組み合わせは以下の通りである。

IABIG-02 Computer Graphics 5 

これは質問に関連が、これは私が達成したいものですされていません。

入力

(IABIG-02 Computer Graphics 5) or ((AIBJH88 Computer Vision 5) and (AIKKH10 Computer Architecture 5)) 

出力

ここ
T or (F and T) 
+0

あなたはどのコードを試しましたか?投稿する。 "or"と "and"の文字列を分割して余分な括弧を取り除くだけで済みます。残りの部分はあなたが探しているものになります。 – Blitzkr1eg

+0

これは私がちょうど答えた質問に非常に似ています - [http://stackoverflow.com/questions/36787560/how-to-evaluate-custom-parenthesis-expression-in-c](http://stackoverflow.com/質問/ 36787560/how-to-evaluate-custom-parenthesis-expression-in-c)を参照してください。それはC#ですが、あなたのニーズに適応するのは難しいはずはありません。 – ClasG

+0

Nicolas Filottoが与えた答えであるBlitzkr1egの提案がありがとうございました。 – Martin

答えて

1

それを行うための潜在的な方法ですが、私はそれを実装する任意のきれいな方法を見つけることができませんでした:

String value = "(IABIG-02\tComputer Graphics\t5) or ((AIBJH88\tComputer Vision\t5) and (AIKKH10\tComputer Architecture\t5))"; 
Pattern pattern = Pattern.compile("\\((\\w|-)+\\t\\w+(\\w+)*\\t\\d\\)"); 
Matcher matcher = pattern.matcher(value); 
StringBuilder builder = new StringBuilder(value.length()); 
Map<String, Character> replacements = new HashMap<>(); 
char c = 'A'; 
int index = 0; 
while (matcher.find(index)) { 
    builder.append(value, index, matcher.start()); 
    String found = matcher.group(); 
    Character replacement = replacements.get(found); 
    if (replacement == null) { 
     replacement = c++; 
     replacements.put(found, replacement); 
    } 
    builder.append(replacement); 
    index = matcher.end(); 
} 
if (index < value.length()) { 
    builder.append(value, index, value.length()); 
} 

System.out.println(builder); 

出力:

A or (B and C) 

それはで見つかったすべてのパターンを置き換えますAから始まる置換文字。以前は同じ正確なパターンに与えられた文字を再利用できるように、私はMapを使用します。

関連する問題