一、java
正則表達式的兩種應用場景:1)查找特定信息(搜索) 2)查找並編輯特定信息(替換)
\ 將下一個字符標記為或特殊字符、或原義字符、或向后引用、或八進制轉義符。例如:序列 '\\' 匹配 "\",而 '\(' 則匹配 "("
[xyz]字符集合。匹配所包含的任意一個字符。例如,“[abc]”可以匹配“plain”中的“a”
[^xyz]負值字符集合。匹配未包含的任意字符。例如,“[^abc]”可以匹配“plain”中的“plin”。
java 匹配整個字符串
搜索單詞car,不區分大小寫。整個字符串進行搜索 "[Cc][Aa][Rr]"
public static void main(String[] args) { String regex = "^[Cc][Aa][Rr]$"; Pattern pattern = Pattern.compile(regex); Matcher match = pattern.matcher("car"); boolean flag = match.matches(); System.out.println(flag); Matcher match1 = pattern.matcher("car "); boolean flag1 = match1.matches(); System.out.println(flag1); Matcher match2 = pattern.matcher(" car "); boolean flag2 = match2.matches(); System.out.println(flag2); Matcher match3 = pattern.matcher("CAR"); boolean flag3 = match3.matches(); System.out.println(flag3);
Matcher match4 = pattern.matcher("cAr"); boolean flag4 = match4.matches(); System.out.println(flag4);
Matcher match5 = pattern.matcher("carb");
boolean flag5 = match5.matches();
System.out.println(flag5);
}
true
false
false
true
true
false
\b[Cc][Aa][Rr]\b 匹配car、CAR、CAr、Car (car不區分大小寫的),但是不能匹配空格等
二、javascript
RegExp 對象的方法
RegExp 對象有 3 個方法:test()、exec() 以及 compile()。
test() 方法檢索字符串中的指定值。返回值是 true 或 false。
exec() 方法檢索字符串中的指定值。返回值是被找到的值。如果沒有發現匹配,則返回 null。
compile() 方法用於改變 RegExp。
compile() 既可以改變檢索模式,也可以添加或刪除第二個參數。
javascript 匹配字符串
function myFunction(){
var patt1=new RegExp("[Cc][Aa][Rr]");
alert(patt1.test("The is my car")+" "+patt1.exec("my car"));
patt1.compile("e");//正則現在被改為"e"
alert(patt1.test("my car")+" "+patt1.exec("my car"));//由於字符串中不存在 "e"
} 彈出提示框 true car
false null
詳見:http://www.w3school.com.cn/js/js_obj_regexp.asp
RegExp 對象
RegExp 對象表示正則表達式,它是對字符串執行模式匹配的強大工具。
創建 RegExp 對象的語法:
new RegExp(pattern, attributes);
參數
參數 pattern 是一個字符串,指定了正則表達式的模式或其他正則表達式。
參數 attributes 是一個可選的字符串,包含屬性 "g"、"i" 和 "m",分別用於指定全局匹配、區分大小寫的匹配和多行匹配。ECMAScript 標准化之前,不支持 m 屬性。如果 pattern 是正則表達式,而不是字符串,則必須省略該參數。
RegExp 對象方法
方法 | 描述 | FF | IE |
---|---|---|---|
compile | 編譯正則表達式。 | 1 | 4 |
exec | 檢索字符串中指定的值。返回找到的值,並確定其位置。 | 1 | 4 |
test | 檢索字符串中指定的值。返回 true 或 false。 | 1 | 4 |
支持正則表達式的 String 對象的方法
方法 | 描述 | FF | IE |
---|---|---|---|
search | 檢索與正則表達式相匹配的值。 | 1 | 4 |
match | 找到一個或多個正則表達式的匹配。 | 1 | 4 |
replace | 替換與正則表達式匹配的子串。 | 1 | 4 |
split | 把字符串分割為字符串數組。 | 1 | 4 |
參見:http://www.w3school.com.cn/jsref/jsref_obj_regexp.asp