2012-04-18 3 views
0

정규식 패턴 일치가 반복적으로 작동하지 않습니다.

(c + 또는 * 또는/d) ............. 패턴 일치를 구현하고 싶습니다. 여러 번에 .

다음 패턴을 사용하지만 재귀 적으로 작동하지 않습니다. 첫 번째 그룹을 읽는 중입니다.

Pattern pattern; 
String regex="(([0-9]*)([+,-,/,*])([0-9]*)*)"; 
pattern=Pattern.compile(regex); 
Matcher match = pattern.matcher(userInput); 
+0

어떤 상황에서 이것을 사용하고 있습니까? 정규식으로 테스트 할 샘플 텍스트를 줄 수 있습니까? –

+1

확인 15-9 * 12/5 + 9 * 4 사용자 입력으로 이것을 구문 분석하고이 표현식을 계산해야합니다. –

+0

계산 또는 확인 하시겠습니까? 정규 표현식은 매칭을 위해 사용되며, 계산은 체크하지 않습니다. –

답변

0

당신이 순서의 종류와 일치해야하는 정규식은 이것이다 :

\s*-?\d+(?:\s*[-+/*]\s*-?\d+)+\s*

이 구성 요소 부품의에의 그를 분해하자! 공백이 일치하지 않을 경우

\s*   # Optional space 
-?    # Optional minus sign 
\d+   # Mandatory digits 
(?:   # Start sub-regex 
    \s*   # Optional space 
    [-+*/]  # Mandatory single arithmetic operator 
    \s*   # Optional space 
    -?   # Optional minus sign 
    \d+   # Mandatory digits 
)+    # End sub-regex: want one or more matches of it 
\s*   # Optional space 

는 (그 \s* 모두 제거하고 꽤 많은 사용자를 놀라게된다는 점에 유의.자바에서 리터럴 문자열로 위를 인코딩 할 때 지금)

는 (컴파일하기 전에) 당신은 그 안에 \ 각 문자를 탈출 조심해야합니다

String regex="\\s*-?\\d+(?:\\s*[-+/*]\\s*-?\\d+)+\\s*"; 

다른 점은 알고 있어야 이 정규 표현식을 Java 용 조각으로 분리하여 구문 분석 및 표현 평가 트리를 작성하지 않습니다. 그냥 (코드의 나머지 부분과 함께) 전체 문자열과 일치하는지 아닌지를 나타냅니다. (심지어 괄호를 넣는 것조차도 도움이되지 않을 것입니다. 어떤 반복 형식 안에 넣어지면 문자열의 첫 번째 위치 만보고합니다.) 올바르게 수행하는 가장 간단한 방법은 파서 생성기를 사용하는 것입니다. Antlr (괄호로 묶인 서브 표현식, 연산자 우선 순위 관리 등을 할 수도 있습니다)

+0

음, 고마워. 귀하의 정규식은 단지 나를 위해 잘 작동합니다. 스택 구현을 사용할 계획이다. 다시 한 번 감사드립니다. –

+0

@Rohit : "스택 구현"은 LL 파서와 매우 비슷하며 ANTLR은이를 구축하기위한 도구입니다. (LR 파서를 만들 것이라고 생각하는 이름이 있지만 그렇게하지는 않지만 멋진 이름의 레이어를 놓친 또 다른 기회 ...) –

0

당신은 당신은 전체 표현식과 일치해야이

[0-9]+-[0-9]+[\/*-+][0-9]+[\/*-+][0-9]+[\/*-+][0-9]+[\/*-+][0-9]+ 

같은 표현을해야합니다. 표현식의 일부와 일치 할 수없고 패턴이 반복되기 때문에 두 번째 검색을 수행 할 수 없습니다.

참고 : 루비 \는/문자를 제외하고 사용할 수 있으므로 C#에서는 생략하거나 다른 문자로 바꿀 수 있습니다.

Demo

-1

표현식은 +와 같은 특수 문자를 탈출 나던, (,)

이 G \

/\(\d+[\+|-|\/|\*]\d+)\G?/ 

다시

이상 전체 패턴 시도? 의미 이전의 것은 선택 사항입니다 내가 변경

하여 [0-9] * 내가

내가 변경 더 정확하다고 생각 d 개 +를 \ 당신의에 |

+0

아니,'\ G'는 설명과 같이 작동하지 않습니다. 마지막 일치의 경계와 일치합니다. 즉, 마지막 일치가 끝나는 위치를 나타냅니다. – nhahtdh

0

패턴

<!-- 
\((\d|[\+\-\/\\\*\^%!]+|(or|and) *)+\) 

Options:^and $ match at line breaks 

Match the character “(” literally «\(» 
Match the regular expression below and capture its match into backreference number 1 «(\d|[\+\-\/\\\*\^%!]+|(or|and) *)+» 
    Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» 
    Note: You repeated the capturing group itself. The group will capture only the last iteration. Put a capturing group around the repeated group to capture all iterations. «+» 
    Match either the regular expression below (attempting the next alternative only if this one fails) «\d» 
     Match a single digit 0..9 «\d» 
    Or match regular expression number 2 below (attempting the next alternative only if this one fails) «[\+\-\/\\\*\^%!]+» 
     Match a single character present in the list below «[\+\-\/\\\*\^%!]+» 
     Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» 
     A + character «\+» 
     A - character «\-» 
     A/character «\/» 
     A \ character «\\» 
     A * character «\*» 
     A^character «\^» 
     One of the characters “%!” «%!» 
    Or match regular expression number 3 below (the entire group fails if this one fails to match) «(or|and) *» 
     Match the regular expression below and capture its match into backreference number 2 «(or|and)» 
     Match either the regular expression below (attempting the next alternative only if this one fails) «or» 
      Match the characters “or” literally «or» 
     Or match regular expression number 2 below (the entire group fails if this one fails to match) «and» 
      Match the characters “and” literally «and» 
     Match the character “ ” literally « *» 
     Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*» 
Match the character “)” literally «\)» 
--> 

는 스택을 사용해야 파싱 및 처리, 입력 문자열의 계산 알고리즘
. 컨셉은 here입니다.

감사

Cylian
관련 문제