📜  Java中的模式引用(字符串)方法与示例

📅  最后修改于: 2022-05-13 01:54:41.433000             🧑  作者: Mango

Java中的模式引用(字符串)方法与示例

Pattern类的quote(String)方法,用于返回作为参数传递给方法的指定字符串的字面量模式字符串。此方法产生一个等效于 s 的字符串,可用于创建模式。输入序列中的元字符或转义序列将没有特殊含义。如果您编译由 quote 方法返回的值,您将得到一个 Pattern,它与您作为参数传递给方法的字面量字符串匹配。\Q 和 \E 标记字符串的引用部分的开始和结束。

句法:

public static String quote(String s)

参数:此方法接受一个参数s ,它表示要字面化的字符串。

返回值:此方法返回 String 的字面量字符串替换。

下面的程序说明了 quote() 方法:
方案一:

// 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

方案二:

// 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: Java Java.lang.String)