2016-10-31 48 views
-3

我需要驗證在文本文件中的遊戲水平如下格式:用正則表達式驗證字符串不工作

##### 
# #### 
#  # 
### **# # 
# #* *@# 
# * ### 
# ## # 
##  # 
#.$# # 
# #### 
#### 

這裏是我的Java代碼:

static Pattern pattern = Pattern.compile("[\\s#.$*@+]"); 
static BufferedReader br; 
public static void main(String[] args) { 
... 
while ((x = br.readLine()) != null) { 
    System.out.println(x.toLowerCase()); 
    System.out.println(isLineValid(x)); 

} ... }

private static boolean isLineValid(String line) { 
    if (pattern.matcher(line).matches()) { 
     return true; 
    } 
    return false; 
} 

我的正則表達式有什麼問題?因爲我總是弄虛作假。謝謝

+1

正如你在任何情況下,* isLineValid()*返回false比你有所有的情況下錯誤的。 –

+0

爲什麼你只是返回* pattern.matcher(line).matches()*? –

+0

但是問題是爲什麼......我總是隻有這七個字符...... –

回答

3

您只匹配一個字符與您的模式,您需要匹配零/一個或多個與*+量詞。請注意,Matcher#matches()方法需要完整的字符串匹配。

所以,你需要

pattern = Pattern.compile("[\\s#.$*@+]*") 

請注意,您不需要overescape字符類中的某些字符。

此外,isLineValid總是返回,你需要確保一個分支,測試如果線路相匹配的模式將返回真正

Java demo打印 「有效」:

import java.util.*; 
import java.lang.*; 
import java.io.*; 
import java.util.regex.*; 

class Ideone 
{ 
    public static final Pattern pattern = Pattern.compile("[\\s#.$*@+]*"); // < -- Fixed pattern 

    public static void main (String[] args) throws java.lang.Exception 
    { 
     String s = " #####\n# ####\n#  #\n### **# #\n# #* *@#\n# * ###\n# ## #\n##  #\n#.$# #\n# ####\n ####"; 
     if (isLineValid(s)) { 
      System.out.println("Valid"); 
     } else { 
      System.out.println("Not Valid"); 
     } 
    } 

    private static boolean isLineValid(String line) { 
     if (pattern.matcher(line).matches()) { 
      return true;       // <-- Returning TRUE here 
     } 
     return false; 
    } 
} 
相關問題