2014-12-19 35 views
-2

後,我用下面的表達式:如果字符串應該包含';',RegEx匹配之前和特定的字符串

"?:(.*);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 

對於案件1 - 4我得到正確的輸出,而不是56

+2

請張貼工作正則表達式。 – 2014-12-19 09:50:09

+0

RegEx:「?:(。*); GRAYSCALE =([0-9] {1,2} | 1 [0-9] {2} | 2 [0-4] [0-9] | 25 [0 -5]:();?\\ W *)「?我得到正確的輸出爲以上正則表達式。只有當我在GRAYSCALE之前添加任何東西時,纔會返回false。 – MIM 2014-12-19 09:53:20

+0

這不可能是一個工作正則表達式,沒有'\\('in。 – vks 2014-12-19 10:05:52

回答

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 2014-12-19 10:03:45

+0

你可以發表downvote的原因嗎? – 2014-12-19 12:38:25

4

爲什麼這麼做只有一個正則表達式?使用多種工具:

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 

如果使用Java 8,這裏是一些拉姆達濫用(與SEMICOLONGRAYSCALE如上定義):

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把數字檢查他的正則表達式的條件 – 2014-12-19 10:07:36

+0

@AvinashRaj我既不;看起來像一個0到255之間的整數是想要的,這可以做得更有效率外的正則表達式,這是肯定的 – fge 2014-12-19 10:08:49

相關問題