2017-02-15 85 views
-1

我有一種情況,其中相同的模式適用於Java,不適用於Apache常規experssions API。正則表達式與Apache正則表達式

import java.util.regex.*; 
import org.apache.oro.text.regex.MalformedPatternException; 
import org.apache.oro.text.regex.PatternCompiler; 
import org.apache.oro.text.regex.PatternMatcher; 
import org.apache.oro.text.regex.Perl5Compiler; 
import org.apache.oro.text.regex.Perl5Matcher; 

public class PatternExample { 

    public static void main(String[] args) { 
     Pattern pattern = Pattern.compile("^(?=.*?[a-zA-Z])(?=.*?[0-9])[a-zA-Z0-9\\p{Punct}]+"); //working 
     Matcher matcher = pattern.matcher("[email protected]"); 
     System.out.println("Input String matches regex - "+matcher.matches()); 
     match("[email protected]"); 
    } 


    public static MatchResult match(String input) { 
     PatternCompiler compiler = new Perl5Compiler(); 
     PatternMatcher matcher = new Perl5Matcher(); 
     org.apache.oro.text.regex.Pattern pattern = null; 

     if (pattern == null) { 
      try { 
       pattern = compiler.compile("^(?=.*?[a-zA-Z])(?=.*?[0-9])[a-zA-Z0-9\\p{Punct}]+"); 
      } catch (MalformedPatternException e) { 
       System.out.println(e.getMessage()); 
       e.printStackTrace(); 
       return null; 
      } 
     } 
     if (matcher.matches(input, pattern)) { 
      System.out.println("true"); 
     }else{ 
      System.out.println("false"); 
     } 
     return null; 
    } 

} 

上面的代碼是讓輸出的主要方法模式中兩種不同的方式,同時匹配方法提供虛假工作。

基本上我的要求是允許字母數字和Java和JavaScript中的一些特殊字符我使用Perl5Compiler在JavaScript中進行驗證,並且再次使用Java進行驗證。

JavaScript驗證 功能_validatePasswordCharacter(/ *部件* /場){

var regExp; 
    var regExpInput = "^(?=.*?[a-zA-Z])(?=.*?[0-9])[a-zA-Z0-9\\p{Punct}]+"; 
    console.log(regExpInput); 
    try 
    { 
     regExp = new RegExp(regExpInput); 
    } 
    catch (Error) 
    { 
     console.debug('Error while parsing the password charset'); 

     return false; 
    } 

    if (!regExp.test(field.get('value'))) 
    {  
     console.debug('Password not matching regular expression check -- portal.properties'); 
     return false; 
    } 
    else{ 
     console.debug('Password matching regular expression check -- portal.properties'); 
     return true; 
    } 

} 

請建議向前

+0

的JavaScriptŧ這裏是沒有JavaScript在這裏... – Cerbrus

+0

我不知道{Punct}部分;嘗試(只是作爲一個測試)刪除它,並明確說明你想要什麼(在這種情況下:'[!'#$%&'()* +,。/ :; <=>?@ [\]^_'{| }「# – dquijada

+0

[」有些人在遇到問題時想'我知道,我會用正則表達式',現在他們有兩個問題。「](https://blog.codinghorror.com/正則表達式現在你有兩個問題/ /)嚴重的是,你可以極大地簡化事情*不*嘗試在單個正則表達式中完成所有事情*全部在一行中執行並不意味着它會更快或更好。 – VGR

回答

0

還可以將一些測試後,我相信Perl不會有{PUNCT}類此正則表達式應該工作打算:

"^(?=.*?[a-zA-Z])(?=.*?[0-9])[a-zA-Z0-9!"#$%&'()*+,./:;<=>[email protected][\]^_ {|}〜 - ] +「`