2012-10-22 57 views
4

我在將一個php pregmatch轉換爲java時遇到了一些麻煩。我認爲我已經完全正確,但似乎沒有工作。下面是代碼:Preg_match PHP到java的翻譯

原始PHP:

/* Pattern for 44 Character UUID */ 
$pattern = "([0-9A-F\-]{44})"; 
if (preg_match($pattern,$content)){ 
       /*DO ACTION*/ 
      } 

我的Java代碼:

final String pattern = "([0-9A-F\\-]{44})"; 
    public static boolean pregMatch(String pattern, String content) { 
      Pattern p = Pattern.compile(pattern); 
      Matcher m = p.matcher(content); 
      boolean b = m.matches(); 
      return b; 
     } 
if (pregMatch(pattern, line)) { 
         //DO ACTION 
        } 

所以我的測試輸入是: DBA40365-7346-4DB4-A2CF-52ECA8C64091-0

使用一系列的System.out我得到了b = false。

回答

7

要實現的功能,你在你的代碼所做的:

final String pattern = "[0-9A-F\\-]{44}"; 
public static boolean pregMatch(String pattern, String content) { 
    return content.matches(pattern); 
} 

然後你就可以將其稱爲:

if (pregMatch(pattern, line)) { 
    //DO ACTION 
} 

你不需要括號中的pattern,因爲這只是創建一個您不使用的匹配組。如果您需要訪問反向引用,則需要使用PatternMatcher類的更高級的正則表達式代碼。

+0

我不能說,如果我想匹配線是問題或沒有。一些示例是:B3AF08DE-7F02-450B-A316-94AB10603956-0 ||| 83202015-E001-422C-9792-1D298893A289-0 ||| DBA40365-7346-4DB4-A2CF-52ECA8C64091-0這些代碼行有什麼問題,他們失敗了,或者在我的代碼中可能有其他錯誤? – Evilsithgirl

+0

這些字符串長度爲38個字符,並且您的正則表達式試圖將44個字符與「{44}」匹配。使用正則表達式pattner'[0-9A-F \\ - ] {38}',它將匹配每一個這些值。如果要匹配38到44個字符的字符串,請使用'[0-9A-F \\ - ] {38,44}' – doublesharp

6

你可以只使用String.matches()

if (line.matches("[0-9A-F-]{44}")) { 
    // do action 
}