java中使用正则表达式

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);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值