2013-12-17 3 views
2

숫자 표현식을 분할해야합니다.숫자 표현식을 분할하는 정규식

0: 1+1 |1| |1| 
1: 1-1 |1| |1| 
2: 22*43 |22| |43| 
3: 25/17 |25| |17| 
4: -3 * -3 || |3| 

문제는 라인 4 : 기본은 내가 얻을

public static void main(String[] args) { 
    String [] a = {"1+1", "1-1", "22*43", "25/17", "-3 * -3"}; 
    String [] z; 
    for(int i = 0; i < a.length; i++){ 
     z = a[i].split("[\\D]"); 
     System.out.println(i + ": " + a[i] + " |" + z[0] + "| " + "|" + z[1] + "|"); 
    } 
} 

을 시도했습니다 ... 쉽지만, 어떤이 있어야한다 :

4: -3 * -3 |-3| |-3| 

이 가능 이것을 달성하기 위해 \\D 정규식을 향상시키기 위해?

+0

정규 표현식 \ D는 공백 문자도 찾습니다. [^ \ d \ s] 대신에 숫자 나 공백을 제외하고 사용할 수 있습니다. –

답변

1

여기서 문제는 \D- 표지를 캡처한다는 것입니다.

한 가지 해결 방법은 표현식의 시작 부분에 - 부호를 처리하고 특별한 경우 두 가지 경우 연산자를 사용하는 것입니다.

더 우아한 해결책은 문법을 구현하는 것입니다. http://lukaszwrobel.pl/blog/math-parser-part-2-grammar을 참조하십시오.

0

이것은 당신이 표현 연결할하지 않는 한, 당신의 필요를 위해 작동합니다 : 시도

"(?<=\\d)\\s*\\D\\s*(?=\\d|-)" 
0

을이 :

public static void main(String[] args) { 
     String[] a = {"1+1", "1-1", "22*43", "25/17", "-3 * -3"}; 
     for (int i = 0; i < a.length; i++) { 
      String s = a[i].replaceAll(" ", ""); 
      String z2 = s.replaceAll("(.*[\\d])([\\D])(.*)", "|$1|"+"|$3|"); 
      System.out.println(z2); 
     } 
    } 

당신의 표현을 지원하기 위해 재귀를 사용하려면 모든 길이는 다음과 같습니다.

static Pattern p; //declare this member in the class 

public static void main(String[] args) { 
    p = Pattern.compile("(.*[\\d])([\\D])(.*)"); 
    String[] a = { "1+1", "1-1", "22*43", "25/17", "-3 * -3 - -4" }; 
    for (int i = 0; i < a.length; i++) { 
     String s = a[i].replaceAll(" ", ""); 
     split(s); 
     System.out.println("\n"); 
    } 
} 

static void split(String s) { 
    Matcher m = p.matcher(s); 
    if (!m.matches()) 
     return; 
    else { 
     for (int i = 1; i <= 3; i += 2) { 
      if (m.group(i).length() < 3) { 
       System.out.print(" |" + m.group(i) + "| "); 
      } else 
       split(m.group(i)); 
     } 
    } 
}