2014-12-19 3 views
-2

후 나는 다음과 같은 표현을 사용하고 있습니다 : 경우 1를 들어문자열에 ';'을 포함해야하는 경우 일치시킬 정규 표현식입니다. 전 특정 문자열

"?:(.*);GRAYSCALE=([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])(?:;\\w*)?" 
1. Input: GRAYSCALE=(120) --> Expected output: true 
2. Input: GRAYSCALE=(120); --> Expected output: true 
3. Input: GRAYSCALE=(120);abcd --> Expected output: true 
4. Input: GRAYSCALE=(120)abcd --> Expected output: false 
5. Input: abGRAYSCALE=(120); --> Expected output: false 
6. Input: abc;GRAYSCALE=(120);acx --> Expected output: true 

- 나는 올바른 출력을 얻고 4,하지만 56합니다.

+2

작업 정규식을 게시하시기 바랍니다 : 자바 8 사용하는 경우

private static final Pattern SEMICOLON = Pattern.compile(";"); private static final Pattern GRAYSCALE = Pattern.compile("GRAYSCALE=\\((\\d+\\))"); // Test... final String[] splits = SEMICOLON.split(input); Matcher matcher; boolean found = false; String inParens; int number; for (final String candidate: splits) { matcher = GRAYSCALE.matcher(candidate); if (!matcher.find()) continue; inParens = matcher.group(1); try { number = Integer.parseInt(inParens); break; } catch (NumberFormatException e) { // overflow continue; } } // test "number" here 

, 여기에 (위와 같이 정의 SEMICOLONGRAYSCALE와) 일부 람다 남용이다. –

+0

RegEx : "? : (. *); GRAYSCALE = ([0-9] {1,2} | 1 [0-9] {2} | 2 [0-4] [0-9] | 25 [0 -5]) (? :; \\ w *)? " 위 정규식에 대한 정확한 출력을 얻고 있습니다. GRAYSCALE 전에 아무것도 추가하지 않는 경우에만 false를 반환합니다. – MIM

+0

작동하지 않는 regex.there는'\\ ('가 없습니다.) – vks

답변

2

시작 부분에 단어 경계를 추가하고 처음에 ;을 선택 사항으로 만드십시오. 그리고 개폐 괄호 ()과 일치하는 패턴을 추가해야합니다.

(.*?)\\b;?GRAYSCALE=\\(([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\)(?:;\\w*)?$ 

DEMO

String[] inputs = { 
     "GRAYSCALE=(120)",// -- Expected output: True 
     "GRAYSCALE=(120);",// -- Expected output: True 
     "GRAYSCALE=(120);abcd",// -- Expected output: True 
     "GRAYSCALE=(120)abcd",// -- Expected output: False 
     "abGRAYSCALE=(120)",// -- Expected output: False 
     "abc;GRAYSCALE=(120);acx" // --> Expected output: true 
}; 

Pattern p = Pattern.compile("(.*?)\\b;?GRAYSCALE=\\(([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\)(?:;\\w*)?$"); 
for (String input: inputs) { 
    Matcher m = p.matcher(input); 
    System.out.printf("%s found? %b%n", input, m.find()); 
} 

출력 :

GRAYSCALE=(120) found? true 
GRAYSCALE=(120); found? true 
GRAYSCALE=(120);abcd found? true 
GRAYSCALE=(120)abcd found? false 
abGRAYSCALE=(120) found? false 
abc;GRAYSCALE=(120);acx found? true 

DEMO

+0

당신은 남자입니다! 굉장합니다. – MIM

+0

downvote에 대한 이유를 게시 할 수 있습니까? –

4

왜 하나의 정규식이 할? 여러 가지 도구를 사용

final Optional<String> opt = SEMICOLON.splitAsStream().map(GRAYSCALE::matcher) 
    .filter(Matcher::find).map(m -> m.group(1)).findFirst(); 

if (!opt.isPresent()) { 
    // no luck 
} 

try { 
    Integer.parseInt(opt.get()); 
    // Found at least an integer 
} catch (NumberFormatException e) { 
    // overflow 
} 
+0

op를 사용하는 이유가 무엇인지 모르겠습니다. 그의 정규식에서 조건을 확인하십시오. –

+0

@AvinashRaj 나도; 0과 255 사이의 정수처럼 보이는 이것은 훨씬 더 효율적으로 할 수 있습니다 정규식 밖에서 확실히 그게 – fge

관련 문제