1、?:?- 非捕獲組
語法:?(?:pattern)
作用: 創建一個分組但不捕獲匹配結果,不會將匹配的文本存儲到內存中供后續使用。
優勢:
- 提高性能和效率
- 不占用編號(不會影響后續捕獲組的編號)
- 減少內存使用
// 使用捕獲組
let regex1 = /(hello|hi) world/;
let match1 = "hello world".match(regex1);
console.log(match1); // ["hello world", "hello"]// 使用非捕獲組
let regex2 = /(?:hello|hi) world/;
let match2 = "hello world".match(regex2);
console.log(match2); // ["hello world"]
在以上例子中,除了完整匹配外,還捕獲了"hello"。而在第二個例子中,只返回了完整匹配,不會捕獲括號內的內容。
2、?=?- 正向先行斷言
語法:?(?=pattern)
作用: 匹配后面跟著特定模式的位置,但不消耗這些字符(零寬度斷言)。
特點:
- 只斷言位置,不匹配實際字符
- 不會將斷言的內容包含在最終匹配結果中
// 匹配后面是"元"的數字
let regex = /\d+(?=元)/;
let text = "價格是100元";
let match = text.match(regex);
console.log(match); // ["100"]// 匹配后面是閉標簽的所有內容
let html = "<div>內容</div>";
let content = html.match(/.+(?=<\/div>)/);
console.log(content); // ["<div>內容"]
在這個例子中,正向先行斷言確保了特定內容存在于匹配之后,但不包含在匹配結果中。
3、?!?- 負向先行斷言
語法:?(?!pattern)
作用:?匹配后面不跟著特定模式的位置。
特點:
- 零寬度斷言,只匹配位置
- 用于排除某些模式
// 匹配不以數字結尾的單詞
let regex = /\b\w+(?!\d)\b/g;
let text = "apple1 banana orange2";
let matches = text.match(regex);
console.log(matches); // ["banana"]// 匹配不后接元的數字
let priceText = "100元 200美元 300";
let numbers = priceText.match(/\d+(?!元)/g);
console.log(numbers); // ["200", "300"]
?第一個例子匹配不以數字結尾的單詞,第二個例子匹配后面不跟"元"的數字。
4、?<=?- 正向后行斷言
語法:?(?<=pattern)
作用:?匹配前面有特定模式的位置。
特點:
- 零寬度斷言,查看匹配位置之前的內容
- 不消耗字符,不包含在匹配結果中
// 匹配前面是貨幣符號的數字
let regex = /(?<=[$¥€£])(\d+(\.\d+)?)/g;
let text = "$100 ¥200 €300";
let matches = text.match(regex);
console.log(matches); // ["100", "200", "300"]// 匹配標簽內的內容
let html = "<div>內容</div>";
let content = html.match(/(?<=<div>).*(?=<\/div>)/);
console.log(content); // ["內容"]
第一個例子匹配前面有貨幣符號的數字,第二個例子匹配div標簽內的內容。
5、?<!?- 負向后行斷言
語法:?(?<!pattern)
作用: 匹配前面沒有特定模式的位置。
特點:
- 零寬度斷言,排除特定前綴
- 不消耗字符,只斷言位置
// 匹配不在discount-后面的數字
let regex = /(?<!discount-)\d+/g;
let text = "price-100 discount-50 item-200";
let matches = text.match(regex);
console.log(matches); // ["100", "200"]// 匹配不以https://開頭的URL
let urlRegex = /(?<!https:\/\/)www\.\w+\.\w+/g;
let urls = "http://www.example.com https://www.secure.com";
let httpUrls = urls.match(urlRegex);
console.log(httpUrls); // ["www.example.com"]
第一個例子匹配不在"discount-"后面的數字,第二個例子匹配不以"https://"開頭的URL。