java中使用正则表达式

来源:百度文库 编辑:神马文学网 时间:2024/05/03 06:05:10
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);
}
}