2016-09-29 27 views
0

我正在嘗試編寫一個Java方法,它將確定(true或false)特定字符串是否匹配animal<L_OPERAND,R_OPERAND>的正則表達式,其中L_OPERAND可以是以下任何值: dog,cat, sheepR_OPERAND可以是以下值中的任何一個:red,blue。所有值均爲區分大小寫和空格區分Java正則表達式不適用於可能值的操作數組

一些例子:

animal<fizz,cat>   => false; fizz is not a valid L_OPERAND value 
animAl<dog,blue>   => false; animAl contains an upper-case char (illegal) 
animal<dog,sheep>   => false; sheep is not a valid R_OPERAND value 
animal<dog, blue>   => false; contains whitespace between ',' and 'blue' (no whitesapce allowed) 
animal<dog,blue>   => true; valid 
animal<cat,red>   => true; valid 
animal<sheep,blue>  => true; valid 

我迄今爲止最好的嘗試:

public class RegexExperiments { 
    public static void main(String[] args) { 
     boolean b = new RegexExperiments().isValidAnimalDef("animal<dog,blue>"); 
     System.out.println(b); 
    } 

    public boolean isValidAnimalDef(String animalDef) { 
     String regex = "animal<[dog,cat,sheep],[red,blue]>"; 
     if(animalDef.matches(regex)) { 
      return true; 
     } else { 
      return false; 
     } 
    } 
} 

雖然我沒有得到任何異常,我得到false每一個類型的輸入字符串(animalDef)我通過了。顯然,我的正則表達式很糟糕。任何人都可以發現我要去哪裏?

+2

'[狗,貓,羊]'匹配列出的單個字符中的一個,你可能想要的是一個像'(狗|貓|羊)'的替代品' –

+0

謝謝+1!把它變成答案,綠色支票就是你的! – smeeb

+0

@SebastianProske:如果您願意,您可以發佈答案。 –

回答

1

您的問題在於[dog,cat,sheep][red,blue]結構。 []代表一個字符類,它匹配裏面包含的單個字符。第一個是,acdeghopst,第二個是,bdelru。所以你目前匹配的字符串如animal<d,b>甚至animal<,,,>

你在追求的是一個分組結構和一個交替的組合。交替由|提供,例如, dog|cat|sheep將匹配dogcatsheep。當你想在更大的模式中進行這種交替時,你必須將它包含在一個組中。 (對於這種情況)最簡單的分組結構是以(開始並以)結尾的捕獲組。

您的最終模式可能是animal<(dog|cat|sheep),(red|blue)>

0

嘗試

String regex = "animal<(dog|cat|sheep),(red|blue)>"; 
0

您可以使用正則表達式animal<(dog|cat|sheep),(red|blue)>

輸出

false 
false 
false 
false 
true 
true 
true 

代碼

import java.util.regex.*; 

public class HelloWorld { 
    public static void main(String[] args) { 
     System.out.println(filterOut("animal<fizz,cat>")); 
     System.out.println(filterOut("animAl<dog,blue>")); 
     System.out.println(filterOut("animal<dog,sheep>")); 
     System.out.println(filterOut("animal<dog, blue>")); 
     System.out.println(filterOut("animal<dog,blue>")); 
     System.out.println(filterOut("animal<cat,red>")); 
     System.out.println(filterOut("animal<sheep,blue>")); 
    } 

    public static boolean filterOut(String str) { 
     Matcher m = Pattern.compile("animal<(dog|cat|sheep),(red|blue)>").matcher(str); 
     if (m.find()) return true; 
     else   return false; 
    } 
}