java matcher函数,Java中的Matcher regionStart()方法与示例

java.util.regex.Matcher类表示执行各种匹配操作的引擎。该类没有构造函数,可以使用类java.util.regex.Pattern的matchs()方法创建/获取该类的对象。

这个(Matcher)类的regionStart()方法返回一个整数值,该整数值表示当前匹配器对象的起始索引。

例子1import java.util.Scanner;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class RegionStartExample {

public static void main(String[] args) {

//Regular expression to accepts 6 to 10 characters

String regex = "[#]";

System.out.println("Enter a string: ");

Scanner sc = new Scanner(System.in);

String input = sc.nextLine();

//Creating a pattern object

Pattern pattern = Pattern.compile(regex);

//Creating a Matcher object

Matcher matcher = pattern.matcher(input);

//Setting region to the input string matcher.region(2, 4);

//Switching to transparent bounds

if(matcher.find()) {

System.out.println("Match found");

} else {

System.out.println("Match not found");

}

System.out.println("Starting of the region: "+ matcher.regionStart());

}

}

输出结果Enter a string:

#sample text

Match not found

Starting of the region: 2

例子2import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class RegionStartExample {

public static void main(String[] args) {

String regex = "(.*)(\\d+)(.*)";

String input = "124 This is a sample Text, 1234, with numbers in between.";

//Creating a pattern object

Pattern pattern = Pattern.compile(regex);

//Creating a Matcher object

Matcher matcher = pattern.matcher(input);

//Setting the region of the matcher

matcher.region(5, 20);

if(matcher.matches()) {

System.out.println("Match found");

} else {

System.out.println("Match not found");

}

System.out.print("Start of the region: "+matcher.regionStart());

}

}

输出结果Match not found

Start of the region: 5

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值