3. Java 中使用正則表達式
3.1 正則表達式的創(chuàng )建
JDK中自帶正則表達式引擎(java.util.regex)是從 1.4版本開(kāi)始的,以前的版本如果需要正則表達式,需要使用第三方提供的庫。而微軟提供的虛擬機 Java VM 停留在 1.1 版本,因此,在微軟提供的Java 虛擬機中也沒(méi)有自帶正則表達式引擎。
使用 java.util.regex 的方法如下:
import java.util.*;
......
Pattern p = Pattern.compile("\\$(\\d+)");
Matcher m = p.matcher("it costs $23");
Pattern 的 matcher() 方法只是得到了一個(gè)包含“字符串信息”和“表達式信息”的對象,而并沒(méi)有進(jìn)行任何的匹配或者其他操作。
3.2 查找匹配
對字符串的匹配以及其他操作,將在 Matcher 對象上進(jìn)行:
boolean found = m.find();
if( found )
{
String foundstring = m.group();
int beginPos = m.start();
int endPos = m.end();
String found1 = m.group(1); // 括號內匹配內容
}
如果要從指定位置開(kāi)始匹配,可以使用 m.find(pos)。
3.3 替換
替換操作也是在 Matcher 對象上進(jìn)行:
String result = m.replaceAll("¥$1");
得到的 result 是一個(gè)新字符串,不影響原來(lái)的字符串。
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);
}
}
聯(lián)系客服