2016-04-22 92 views
1

我有一個字符串表達式是這樣的:如何在字符串表達式中查找字符串模式Java?

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

我要承認所有(代碼名稱學分)組合的字符串,並用值替換它們。

代碼是字母和數字的組合。

名稱是單詞的組合,由單個空格分隔,單詞可以包含字母和數字。

貸方是一個數字。

每個組件都由標籤分開。

(代碼名稱學分)組合的實際例子如下:

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

你試過了什麼代碼?發表它。 您只需將字符串拆分爲「或」和「和」,然後去掉額外的括號。其餘的部分將是你在找什麼。 – Blitzkr1eg

+0

這與我剛剛回答的問題非常相似 - [http://stackoverflow.com/questions/36787560/how-to-evaluate-custom-parenthesis-expression-in-c](http://stackoverflow.com/問題/ 36787560 /如何做評估,定製括號表達式-C)。這是C#,但不應該很難適應您的需求。 – ClasG

+0

感謝您的建議@ Blitzkr1eg,Nicolas Filotto給出的答案給出了我想要的全部內容。 – 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爲了能夠重複使用先前給予相同確切模式的字符。

相關問題