java中使用正则表达式

在java中要构造一个功能强大的正则表达式对象,需要导入java.util.regex包。
java.util.regex 包主要包括以下三个类:

  • Pattern 类:
    pattern 对象是一个正则表达式的编译表示。Pattern 类没有公共构造方法。要创建一个 Pattern 对象,你必须首先调用其公共静态编译方法(static Pattern.comfile()),它返回一个 Pattern 对象。该方法接受一个正则表达式作为它的第一个参数。
  • Matcher 类:
    Matcher 对象是对输入字符串进行解释和匹配操作的引擎。与Pattern 类一样,Matcher 也没有公共构造方法。你需要调用 Pattern 对象的 matcher 方法来获得一个 Matcher 对象。
  • PatternSyntaxException:
    PatternSyntaxException 是一个非强制异常类,它表示一个正则表达式模式中的语法错误。

下面是java中使用正则表达式的具体使用例子:

一、匹配(查找)

通过调用Pattern.matcher()方法,并传入一个字符串参数,从而得到一个Matcher对象。我们可以使用Matcher上的方法来判断各种不同类型的匹配是否成功,包括:

boolean matches()
boolean lookingAt()
boolean find()
boolean find(int start)

(1)matches()方法:用来判断整个输入字符串是否匹配正则表达式模式.简单
(2)lookingAt()方法:用来判断该字符串(不必是整个字符串)的起始部分是否能够匹配模式。
(3)find()方法:用来查找多个匹配。
(4)find(int start):同样用于查找,不同的是接受一个整数作为参数,该整数表示字符串中字符的位置,并以其作为搜索的起点。
下面例子简单使用这些方法:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
 * 使用Matcher对象的方法进行不同类型的匹配
 */
public class Demo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub		
		/*
		 * matchers()的使用
		 */
		String s1="sss111";
		String s2="111";		
		Pattern pattern=Pattern.compile("\\d+");
		Matcher m1=pattern.matcher(s1);
		Matcher m2=pattern.matcher(s2);
       System.out.println(m1.matches());//输出结果:false
       System.out.println(m2.matches());//输出结果:true
       /*
        * lookingAt()的使用
        */
		String s3="sss111";
		String s4="111sss";
		System.out.println(pattern.matcher(s3).lookingAt());//输出结果:false
		System.out.println(pattern.matcher(s4).lookingAt());//输出结果:true   
		/*
		 * find()和find(int start)方法的使用
		 * 
		 */
			 Matcher matcher=Pattern.compile("\\w+").matcher("Evening is full of the linnet's wings");
			 while(matcher.find()) {//输出结果:Evening is full of the linnet s wings
				 System.out.print(matcher.group()+" ");
			 }
			 System.out.println();
			 int i=0;
			 while(matcher.find(i)) {//不断地重新设定搜索的起始位置(向右移一位)来遍历字符串
				 System.out.print(matcher.group()+" ");
				 i++;
			 }
			 /*
			  * 运行结果:Evening vening ening ning ing ng g is is s full full ull ll l of of f the 
			  * the he e linnet linnet innet nnet net et t s s wings wings ings ngs gs s 
			  */
	}

}

二、替换

替换的方法如下:

方法说明
public String replaceFirst(String replacement)以参数字符串replacement替换掉第一个匹配成功的部分
public String replaceAll(String replacement)以参数字符串replacement替换所有匹配成功的部分
public Matcher appendReplacement(StringBuffer sb, String replacement)实现渐进式的替换。
public StringBuffer appendTail(StringBuffer sbuf)在执行了一次或多次appendReplacement()之后,将字符串的余下的部分复制到sbuf中

下面使用这些方法:

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class ReplaceDemo {

	public static void main(String[] args) {
		String s="Here's a   block   of text to    use as input to the regular expression matcher."
				+ "Note that we'll first extract the block of by looking for the special delimiters,then process the extracted block";
		/*
		 * 使用replaceAll将字符串中的两个或两个以上的空格的地方替换为一个空格
		 */
		Matcher mInput=Pattern.compile(" {2,}").matcher(s);
		s=mInput.replaceAll(" ");
		System.out.println(s);
		/*
		 * 使用String对象的replaceAll()实现,开销更小
		 * 	s=s.replaceAll(" {2,}", " ");
         *	System.out.println(s);
		 */
        /*
              * 使用String对象的replaceFirst()实现,将第一个匹配到的元音字母替换为	(VOWEL1)
         */
		s=s.replaceFirst("[aeiou]","(VOWEL1)");
		StringBuffer sbuf=new StringBuffer();//构造sbuf用来保存最终结果
		Pattern p=Pattern.compile("[aeiou]");
		Matcher m=p.matcher(s);
		while(m.find()) {
			/*
			 * 使用appendReplacement()找到的元音字母转换为大写,同时不断增加(包含前面操作的)字符串长度,直到最后一个匹配处。
			 */
			m.appendReplacement(sbuf, m.group().toUpperCase());
		}
		/*
		 * 使用appendTail()将剩余的未处理的部分存入sbuf中
		 */
		m.appendTail(sbuf);
		System.out.println(sbuf);

		

	}

}

三、分割

Pattern对象的split()方法将输入字符串断开成字符串对象数组(使用String.split()也可以实现相同操作),断开边界由正则表达式确定:

String[] split(CharSequence input)
String[] split(CharSequence input,int limit)//第二个参数limit表示限制输入分割成字符串的数量

简单使用例子:

import java.util.Arrays;
import java.util.regex.Pattern;

public class SplitDemo {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
        String input="This!!unusual use!!of exclamation!!points";
        System.out.println(Arrays.toString(Pattern.compile("!!").split(input)));
        //输出结果:[This, unusual use, of exclamation, points]
        System.out.println(Arrays.toString(Pattern.compile("!!").split(input,3)));   ``	```			`````````																																																																																																			
         //输出结果:[This, unusual use, of exclamation!!points]
         /**
         * 使用String.split()也可以实现相同操作:
         */
        System.out.println(Arrays.toString(input.split("!!")));
        System.out.println(Arrays.toString(input.split("!!",3)));
	}
}

PatternSyntaxException 类的方法

PatternSyntaxException 类提供了下面的方法来帮助我们查看发生了什么错误。

方法说明
public String getDescription()获取错误的描述。
public int getIndex()获取错误的索引。
public String getPattern()获取错误的正则表达式模式。
public String getMessage()返回多行字符串,包含语法错误及其索引的描述、错误的正则表达式模式和模式中错误索引的可视化指示。

参考书籍:《Thinking in Java》
参考文档:Java 正则表达式|菜鸟教程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值