java pattern.quote_Java Pattern quote(String)用法及代码示例

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

用法:

public static String quote(String s)

参数:此方法接受单个参数s,该参数s表示要被字符串化的字符串。

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

以下示例程序旨在说明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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值