您的位置:首页 > 编程语言 > Java开发

java中使用正则表达式

2006-06-02 10:54 337 查看
3. Java 中使用正则表达式
3.1 正则表达式的创建
    JDK 中自带正则表达式引擎(java.util.regex)是从 1.4 版本开始的,以前的版本如果需要正则表达式,需要使用第三方提供的库。而微软提供的虚拟机 Java VM 停留在 1.1 版本,因此,在微软提供的 Java 虚拟机中也没有自带正则表达式引擎。

    使用 java.util.regex 的方法如下:

import java.util.*;
......

Pattern p = Pattern.compile("//$(//d+)");
Matcher m = p.matcher("it costs $23");

    Pattern 的 matcher() 方法只是得到了一个包含“字符串信息”和“表达式信息”的对象,而并没有进行任何的匹配或者其他操作。

3.2 查找匹配
    对字符串的匹配以及其他操作,将在 Matcher 对象上进行:

boolean found = m.find();
if( found )
{
    String foundstring = m.group();
    int beginPos = m.start();
    int endPos = m.end();

    String found1 = m.group(1); // 括号内匹配内容
}

    如果要从指定位置开始匹配,可以使用 m.find(pos)。

3.3 替换
    替换操作也是在 Matcher 对象上进行:

String result = m.replaceAll("¥$1");

    得到的 result 是一个新字符串,不影响原来的字符串。

3.4 示例
import java.util.regex.*;

public class RegexExample {

    public static void main(String[] args)
    {
        Pattern p = Pattern.compile("//$(//d+)");
        Matcher m = p.matcher("it costs $23");

        boolean found = m.find();
        if( found )
        {
            String foundstring = m.group();
            System.out.println(foundstring);
           
            int beginPos = m.start();
            int endPos = m.end();
            System.out.println("start:" + beginPos + "/nend:" + endPos);

            String found1 = m.group(1); // 括号内匹配内容
            System.out.println(found1);
        }

        String result = m.replaceAll("¥$1");
        System.out.println(result);
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息