java中字符串匹配_【Java编程】Java中的字符串匹配

package tengwei.com;

import java.util.regex.Pattern;

import javax.swing.JOptionPane;

public class UseMatchesMethod {

public static void main(String args[])

{

String input = JOptionPane.showInputDialog("请输入有效的电子邮件!");

String reg = "[a-zA-Z]\\w*[@]\\w+[.]\\w{2,}";

if(input.matches(reg))

System.out.println("是有效的电子邮件!");

else

System.out.println("不是有效的电子邮件!");

if(Pattern.matches(reg, input))

System.out.println("是有效的电子邮件");

else

System.out.println("不是有效的电子邮件!");

}

}

使用Pattern类和Matcher类判断字符串匹配

类java.util.regex.Pattern用于创建匹配模式(Pattern)和匹配器(Match)。在上面的程序中,我们使用了该类的静态方法matches(reg,input)判断input是否与给定的正则表达式匹配。对于多次匹配,需要重复调用该方法,因此对于重复匹配而言,它的效率不高。如果需要多次使用一种模式,编译一次后重用此模式比每次都调用此方法效率更高。

package tengwei.com;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class UsePattern {

public static void main(String[] args) {

// TODO Auto-generated method stub

String str="We call this the live-code approach."

+"These examples are available from three locations-they are "

+"on the CD that accompanies this book";

Pattern expression = Pattern.compile("[a-zA-Z]+");//创建匹配模式

Matcher matcher=expression.matcher(str);//通过匹配模式得到匹配器

//通过这种方式来进行重复匹配的效率较高

String word=null;

int n=0;

while(matcher.find())//扫描是否有匹配的子串,如果匹配器没有重置,则从当前下一个还没进行匹配的字符开始匹配

{

word=matcher.group();//得到匹配的子串

System.out.println(word+"\t");

if((n+1)%4==0)//每行显示四个单词

System.out.println();

n++;

}

System.out.print("\n单词总数:"+n);

System.out.println("\n单词字母9个及以上的单词有:");

Pattern expression1 = Pattern.compile("[a-zA-Z]{9,}");

Matcher matcher1=expression1.matcher(str);

while(matcher1.find())

{

word=matcher1.group();

System.out.println(word+"\n");

}

System.out.println();

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值