2017-08-11 116 views
0

输入文本的文本文件的内容具有内容如下:验证使用正则表达式

TIMINCY ........许多任意字符含。空格和制表符

细节........许多任意字符incl。空格和制表符

细节........许多任意字符incl。空格和制表符

细节........许多任意字符incl。空格和制表符

。 (任何数量的行包含DETAILS)

TIMINCY ........许多任意字符incl。空格和制表符

细节........许多任意字符incl。空格和制表符

细节........许多任意字符incl。空格和制表符

细节........许多任意字符incl。空格和制表符

(等等)

Q:我需要使用正则表达式来验证文件,以便如果该文件的内容是不 按照相对于上述然后我可以抛出CustomException给出的图案。

请让知道,如果你能帮助。任何帮助热烈赞赏。

String patternString = "TMINCY"+"[.]\\{*\\}"+";"+"["+"DETAILS"+"[.]\\{*\\}"+";"+"]"+"\\{*\\}"+"]"+"\\{*\\};"; 
Pattern pattern = Pattern.compile(patternString); 
     String messageString = null; 
StringBuilder builder = new StringBuilder(); 
     try (BufferedReader reader = Files.newBufferedReader(curracFile.toPath(), charset)) { 
      String line; 
      while ((line = reader.readLine()) != null) { 
       builder.append(line); 
       builder.append(NEWLINE_CHAR_SEQUENCE); 
      } 

      messageString = builder.toString(); 

     } catch (IOException ex) { 
      LOGGER.error(FILE_CREATION_ERROR, ex.getCause()); 
      throw new BusinessConversionException(FILE_CREATION_ERROR, ex); 
     } 
     System.out.println("messageString is::"+messageString); 
     return pattern.matcher(messageString).matches(); 

但它是正确的文件返回FALSE。请帮我用正则表达式。

+0

* CORRECTION ::,我使用的模式是:字符串patternString = “[” + “TMINCY” + “[] \\ {* \\}” + “” +“[ “+” 详情 “+” \\ {* \\} “+”[。]; “+”] “+” \\ {* \\} “+”] “+” \\ {* \\}; “;而且,错过了提到以下内容:private static final String NEWLINE_CHAR_SEQUENCE =“;”; – saiD

+1

编辑您的帖子,而不是写评论。你真的需要使用REGEX吗?你为什么不在循环中逐行阅读? – jeanr

+0

强制性:https://xkcd.com/1171/ – jdv

回答

0

什么像"^(TIMINCY|DETAIL)[\.]+[a-zA-z\s.]+"

"^" - 相匹配的行
"(TIMINCY|DETAIL)"的开始 - 匹配TIMINCY或细节
"[\.]" - 点字符匹配出现一次或多次
"[a-zA-z\s.]+" - 在这里你把允许的字符发生一次或多次

参考:Oracle Documentation

0

你可以试着一行行,当你遍历线

Pattern p = Pattern.compile("^(?:TIMINCY|DETAILS)[.]{8}.*"); 
//Explanation: 
//^: Matches the begining of the string. 
// (?:): non capturing group. 
// [.]{8}: Matches a dot (".") eight times in a row. 
// .*: Matches everything until the end of the string 
// | : Regex OR operator 

String line = reader.readLine() 
Matcher m; 
while (line != null) { 
    m = p.matcher(line); 
    if(!m.matches(line)) 
     throw new CustomException("Not valid"); 
    builder.append(line); 
    builder.append(NEWLINE_CHAR_SEQUENCE); 
    line = reader.readLine(); 
} 

另外:Matcher.matches()返回true,如果整个字符串的正则表达式匹配,我会建议使用Matcher.find()来找到你的模式不想要。

Matcher (Java 7)