Java Pattern quote(String)方法及示例

Java Pattern quote(String)方法及示例

Pattern 类的 quote(String) 方法用于为作为参数传递给方法的指定字符串返回一个字面模式字符串。输入序列中的元字符或转义序列将不会被赋予特殊的含义。如果你编译quote方法返回的值,你会得到一个Pattern,它与你作为参数传递给method的字面字符串相匹配。\Q和\E标记了字符串中被引用部分的开始和结束。

语法

public static String quote(String s)

参数: 该方法接受一个参数s,代表要被字面化的字符串。

返回值: 该方法返回一个替换字符串s的字面字符串。

以下程序说明了quote()方法:
程序1 :

// Java program to demonstrate
// Pattern.quote() method
  
import java.util.regex.*;
  
public class GFG {
    public static void main(String[] args)
    {
        // create a REGEX String
        String REGEX = "ee";
  
        // create the string
        // in which you want to search
        String actualString
            = "geeksforgeeks";
  
        // create equivalent String for REGEX
        String eqREGEX = Pattern.quote(REGEX);
  
        // create a Pattern using eqREGEX
        Pattern pattern = Pattern.compile(eqREGEX);
  
        // get a matcher object
        Matcher matcher = pattern.matcher(actualString);
  
        // print values if match found
        boolean matchfound = false;
        while (matcher.find()) {
            System.out.println("found the Regex in text:"
                               + matcher.group()
                               + " starting index:"
                               + matcher.start()
                               + " and ending index:"
                               + matcher.end());
  
            matchfound = true;
        }
        if (!matchfound) {
            System.out.println("No match found for Regex.");
        }
    }
}

输出:

found the Regex in text:ee starting index:1 and ending index:3
found the Regex in text:ee starting index:9 and ending index:11

程序2

// Java program to demonstrate
// Pattern.quote() method
  
import java.util.regex.*;
  
public class GFG {
    public static void main(String[] args)
    {
        // create a REGEX String
        String REGEX = "welcome";
  
        // create the string
        // in which you want to search
        String actualString
            = "welcome to jungle";
  
        // create equivalent String for REGEX
        String eqREGEX = Pattern.quote(REGEX);
  
        // create a Pattern using eqREGEX
        Pattern pattern = Pattern.compile(eqREGEX);
  
        // get a matcher object
        Matcher matcher = pattern.matcher(actualString);
  
        // print values if match found
        boolean matchfound = false;
        while (matcher.find()) {
            System.out.println("match found");
            matchfound = true;
        }
        if (!matchfound) {
            System.out.println("No match found");
        }
    }
}

输出:

match found

**参考资料: ** https://docs.oracle.com/javase/10/docs/api/java/util/regex/Pattern.html#quote(java.lang.String)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程