繁体   English   中英

Java中具有特殊字符的模式匹配器问题

[英]Pattern matcher issue with special character in java

我想验证字符串模式。如果在string中没有任何特殊字符,它可以与以下代码一起使用。

例如 :

    Pattern p = Pattern.compile("Dear User, .* is your One Time Password(OTP) for registration.",Pattern.CASE_INSENSITIVE);

    Matcher m = p.matcher("Dear User, 999 is your One Time Password(OTP) for registration.");

    if (m.matches()){
        System.out.println("truee");                
    }else{
        System.out.println("false");
    }  // output false 

如果我删除(和),下面的工作正常。

Pattern p = Pattern.compile("Dear User, .* is your One Time Password OTP for registration.",Pattern.CASE_INSENSITIVE);

    Matcher m = p.matcher("Dear User, 999 is your One Time Password OTP for registration.");

    if (m.matches()){
        System.out.println("truee");                
    }else{
        System.out.println("false");
    }  // output true

尝试这个:

Pattern p = Pattern.compile("Dear User, .* is your One Time Password\\(OTP\\) for registration\\.",Pattern.CASE_INSENSITIVE);

Matcher m = p.matcher("Dear User, 999 is your One Time Password(OTP) for registration.");

if (m.matches()){
   System.out.println("truee");                
}else{
  System.out.println("false");
} 

()和。 在正则表达式中使用。 如果您想要正常的行为,就需要逃脱它们。

在regex中,当需要按字面值匹配时,必须始终提防特殊字符。

在这种情况下,您有3个字符: ( (用于打开组), )) (用于关闭组)和. (匹配任何字符)。

要从字面上匹配它们,您需要对其进行转义,或将其放入字符类[...]

固定演示

package com.ramesh.test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternMatcher {

public boolean containsPattern(String input, String pattern) {
    if (input == null || input.trim().isEmpty()) {
        System.out.println("Incorrect format of string");
        return false;
    }
    // “ * ”is replaced by “ .* ” in replaceAll()
    //“ .* ” Use this pattern to match any number, any string (including the empty string) of any characters.
    String inputpattern = pattern.replaceAll("\\*", ".*");
    System.out.println("first input" + inputpattern);
    Pattern p = Pattern.compile(inputpattern);
    Matcher m = p.matcher(input);
    boolean b = m.matches();
    return b;
}

public boolean containsPatternNot(String input1, String pattern1) {
    return (containsPattern(input1, pattern1) == true ? false : true);
}

public static void main(String[] args) {

    PatternMatcher m1 = new PatternMatcher ();
    boolean a = m1.containsPattern("ma5&*%u&^()k5.r5gh^", "m*u*r*");
    System.out.println(a);// returns True

    boolean d = m1.containsPattern("mur", "m*u*r*");
    System.out.println(d);// returns True

    boolean c = m1.containsPatternNot("ma5&^%u&^()k56r5gh^", "m*u*r*");
    System.out.println(c);// returns false

    boolean e = m1.containsPatternNot("mur", "m*u*r*");
    System.out.println(e);// returns false

}

}

输出:true true false false

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM