java matching_Java中具有示例的Matching lookingAt()方法

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

Matcher类的lookingAt()方法从区域的开头开始将给定的输入文本与模式匹配。如果匹配,则此方法返回true,否则返回false。与matches()方法不同,此方法不需要整个区域中的匹配都可以返回true。

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

import java.util.regex.Pattern;

public class Test {

public static void main(String[] args) {

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

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

+ "\n This is the second line in the text "

+ "\n This is third line in the text";

//Creating a pattern object

Pattern pattern = Pattern.compile(regex);

//Creating a Matcher object

Matcher matcher = pattern.matcher(input);

//checking for the match

if(matcher.lookingAt()) {

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

} else {

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

}

}

}

输出结果Match found

例子2import java.util.Scanner;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class LookingAtExample {

public static void main(String args[]) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter String1: ");

String input1 = sc.nextLine();

System.out.println("Enter String2: ");

String input2 = sc.nextLine();

System.out.println("Enter String3: ");

String input3 = sc.nextLine();

String input = input1+"\n"+input2+"\n"+input3;

System.out.println(input);

//Regular expression to match a word that contain digits

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

//Compiling the regular expression

Pattern pattern = Pattern.compile(regex);

//Retrieving the matcher object

Matcher matcher = pattern.matcher(input);

//verifying whether match occurred

boolean bool = matcher.lookingAt();

if(bool) {

System.out.println("Given input contains digit");

} else {

System.out.println("Given input does not contain any digit");

}

}

}

输出结果Enter String1:

sample text2

Enter String2:

data

Enter String3:

sample

sample text2

data

sample

Given input contains digit

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值