⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 e428. escaping special characters in a pattern.txt

📁 这里面包含了一百多个JAVA源文件
💻 TXT
字号:
Any nonalphanumeric character can be escaped with a backslash to remove it's special meaning (if any). This example implements a method that escapes all nonalphanumeric characters. This method is useful when the pattern is retrieved programmatically and it is necessary to search for the pattern literally. 
Another method of escaping the characters in a pattern is to surround the pattern with \Q and \E. The only thing to watch out for is the presence of \E in the pattern, which would end the escaping of the pattern. 

    String patternStr = "i.e.";
    
    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\.
    
    matchFound = Pattern.matches(patternStr, "i.e.");        // true
    matchFound = Pattern.matches(patternStr, "ibex");        // false
    
    // Returns a pattern where all punctuation characters are escaped.
    static Pattern escaper = Pattern.compile("([^a-zA-z0-9])");
    public static String escapeRE(String str) {
        return escaper.matcher(str).replaceAll("\\\\$1");
    }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -