1、若想要将正则表达式视为一个对象来重复使用,就可以使用Pattern的静态方法compile()进行编译。compile()方法会返回一个Pattern实例。这个实例代表正则表达式,以后就可以重复使用这个Pattern实例的matcher()方法来返回一个Matcher实例,该实例代表符合正则式的实例。
- /**
- * 作者:阳光的味道
- * 功能:Patrern、Matcher示例
- * 日期:2010/11/08
- * */
- import ;
- import ;
- public class TestPatterAndMacher {
- public static void main(String[] args) {
- //通过compile()方法创建Pattern实例
- Pattern pattern=("java");
- //通过match()创建Matcher实例
- Matcher matcher=("java Java java JAVA jAva");
- while (())//查找符合pattern的字符串
- {
- ("The result is here :" +
- () + "\n" + "It starts from "
- + () + " to " + () + ".\n");
- }
- }
- }
输出结果:
The result is here :java
It starts from 0 to 4.
The result is here :java
It starts from 10 to 14.
在上面的代码Pattern pattern=("java")改为Pattern pattern=("java",Pattern.CASE_INSENSITIVE)。此时可以不区分大小写地查找。
- /**
- * 作者:阳光的味道
- * 功能:Patrern、Matcher示例
- * 日期:2010/11/08
- * */
- import ;
- import ;
- public class TestPatterAndMacher {
- public static void main(String[] args) {
- //通过compile()方法创建Pattern实例
- Pattern pattern=("java",Pattern.CASE_INSENSITIVE);
- //通过match()创建Matcher实例
- Matcher matcher=("java Java java JAVA jAva");
- while (())//查找符合pattern的字符串
- {
- ("The result is here :" +
- () + "\n" + "It starts from "
- + () + " to " + () + ".\n");
- }
- }
- }
结果:
The result is here :java
It starts from 0 to 4.
The result is here :Java
It starts from 5 to 9.
The result is here :java
It starts from 10 to 14.
The result is here :JAVA
It starts from 15 to 19.
The result is here :jAva
It starts from 20 to 24.
忽略大小的写法也可以有以下简单方法:
- /**
- * 作者:阳光的味道
- * 功能:Patrern、Matcher示例
- * 日期:2010/11/08
- * */
- import ;
- import ;
- public class TestPatterAndMacher {
- public static void main(String[] args) {
- //通过compile()方法创建Pattern实例
- Pattern pattern = ("java");
- //通过match()创建Matcher实例
- Matcher matcher=("java Java java JAVA jAva");
- while (())//查找符合pattern的字符串
- {
- ("The result is here :" +
- () + "\n" + "It starts from "
- + () + " to " + () + ".\n");
- }
- ("Java".matches("(?i)(java)"));
- }
- }
- /*out:
- The result is here :java
- It starts from 0 to 4.
- The result is here :java
- It starts from 10 to 14.
- true*/
- /**
- * 作者:阳光的味道
- * 功能:Patrern、Matcher示例
- * 日期:2010/11/08
- * */
- import ;
- import ;
- public class TestPatterAndMacher {
- public static void main(String[] args) {
- //通过compile()方法创建Pattern实例
- Pattern pattern = ("java",Pattern.CASE_INSENSITIVE);
- //通过match()创建Matcher实例
- Matcher matcher=("java Java java JAVA jAva avafdsafdsaf");
- StringBuffer buffer=new StringBuffer();
- int i=0;
- while (())
- {
- i++;
- if(i%2==0)
- { //偶数项替换为JAVA
- (buffer, "JAVA");
- }
- else { //基数项替换为java
- (buffer, "java");
- }
- }
- (buffer);//将剩余的不匹配部分也追加到buffer中
- (buffer);
- }
- }
- /*out:
- java JAVA java JAVA java avafdsafdsaf
- */