集册 Java实例教程 在模式中转义特殊字符

在模式中转义特殊字符

欢马劈雪     最近更新时间:2020-01-02 10:19:05

536
在模式中转义特殊字符

/**
 * N o w  J a v a  .   c o m 提 供 
**/

import java.util.regex.Pattern;


public class Main {

  public void main(String[] argv) {

    String patternStr = "i.e.";

    // Returns a pattern where all punctuation characters are escaped.


    boolean matchFound = Pattern.matches(patternStr, "i.e.");// true

    matchFound = Pattern.matches(patternStr, "ibex"); // true


    // Quote the pattern; i.e. surround with \Q and \E

    matchFound = Pattern.matches("\\Q" + patternStr + "\\E", "i.e."); // true

    matchFound = Pattern.matches("\\Q" + patternStr + "\\E", "ibex"); // false


    // Escape the pattern

    patternStr = escapeRE(patternStr); // i\.e\.
    /**来自 
     N o  w  J a v a . c o m - 时  代  Java**/


    matchFound = Pattern.matches(patternStr, "i.e."); // true

    matchFound = Pattern.matches(patternStr, "ibex"); // false

  }


  
展开阅读全文