2011-12-21 65 views
2

我有一個程序,它以邏輯表達式的形式接受用戶輸入(例如:(p =>(r || q))),它將字符串通過括號定義的子字符串。我正在使用模式和匹配器。
因此,例如用戶輸入:
((p || q)=> r)
我想要得到2子分別是:
p ||常見
(P || q)的=> R。
但是我只得到這樣的:
(P ||常見使用Java正則表達式來查找具有另一個子字符串的子字符串

這裏是我使用

Scanner scanner = new Scanner(System.in); 
System.out.println("Enter formula: "); 
String formula = scanner.next(); 
Pattern pattern = Pattern.compile("\\((.*?)\\)"); 
Matcher matcher = pattern.matcher(formula); 
     while(matcher.find()) 
     { 
      String s = matcher.group(1); 

      System.out.println(s); 
      } 

的代碼,所以我需要一種方式,程序發現的所有子

+0

正則表達式很不適合此任務。我建議你手動解析或使用解析庫。 – 2011-12-21 18:15:31

回答

2

你不能用正則表達式來做到這一點

因爲使用括號表示你想要做的事超出了正則表達式的能力。正則表達式描述了不能有托架結構的Chomsky-3語法。支架結構可以在喬姆斯基2語法中找到。所以你必須用解析規則定義相應的語法。一個好的圖書館,可能會幫助你實現你想要的是ANTLR

2

正如我在我的評論中所說的,正則表達式根本不處理嵌套括號。但是,如果您有堆棧,手動解析它們非常簡單。以下是一些示例代碼:

public static void main(String[] args) throws InterruptedException { 
    findSubExpressions("((p||q)=>r)"); 
} 

private static void findSubExpressions(String input) { 
    Deque<Integer> startingBrackets = new LinkedList<Integer>(); 

    for (int i = 0; i < input.length(); i++) { 
     char c = input.charAt(i); 
     if (c == '(') { 
      startingBrackets.push(i); 
     } else if (c == ')') { 
      int correspondingStart = startingBrackets.pop(); 
      logSubExpression(input.substring(correspondingStart+1, i)); 
     } 
    } 
} 

private static void logSubExpression(String subExpression) { 
    System.out.println(subExpression); 
} 
相關問題