引言

JavaScript中的正则表达式是处理字符串的强大工具。它允许开发者进行复杂的模式匹配、搜索、替换和验证操作。正则表达式由一系列字符和元字符组成,其中元字符是正则表达式的灵魂,它们定义了匹配的规则和模式。掌握以下关键元字符,将帮助您解锁高效文本处理的技巧。

关键元字符详解

1. 字符匹配

  • .:匹配除换行符以外的任意单个字符。
    
    let regex = /a./g;
    let str = "cat, bat, hat";
    let matches = str.match(regex);
    console.log(matches); // ["cat", "bat", "hat"]
    
  • [ ]:匹配方括号内的任意一个字符(字符类)。
    
    let regex = /[abc]/g;
    let str = "bad cat, mad hat, rad rat";
    let matches = str.match(regex);
    console.log(matches); // ["a", "a", "a"]
    
  • [^]:匹配不在方括号内的任意一个字符(否定字符类)。
    
    let regex = /[^abc]/g;
    let str = "bad cat, mad hat, rad rat";
    let matches = str.match(regex);
    console.log(matches); // ["d", "d", "d"]
    

2. 量词

  • ?:匹配前面的子表达式零次或一次。
    
    let regex = /boon*/g;
    let str = "boon, boonful, boondoggle";
    let matches = str.match(regex);
    console.log(matches); // ["boon", "boon"]
    
  • +:匹配前面的子表达式一次或多次。
    
    let regex = /boon+/g;
    let str = "boon, boonful, boondoggle";
    let matches = str.match(regex);
    console.log(matches); // ["boon", "boon"]
    
  • *****:匹配前面的子表达式零次或多次。
    
    let regex = /boon*/g;
    let str = "boon, boonful, boondoggle";
    let matches = str.match(regex);
    console.log(matches); // ["boon", "oon", "oon"]
    
  • {n}:匹配确定的n次。
    
    let regex = /\d{2,3}/g;
    let str = "There are 12, 23, 1234, 12345 cats.";
    let matches = str.match(regex);
    console.log(matches); // ["12", "23", "1234"]
    
  • {n,}:匹配至少n次。
    
    let regex = /\d{3,}/g;
    let str = "There are 12, 23, 1234, 12345 cats.";
    let matches = str.match(regex);
    console.log(matches); // ["1234", "12345"]
    
  • {n,m}:匹配n到m次。
    
    let regex = /\d{2,4}/g;
    let str = "There are 12, 23, 1234, 12345 cats.";
    let matches = str.match(regex);
    console.log(matches); // ["12", "23", "1234", "12345"]
    

3. 定位符

  • ^:匹配输入字符串的开始位置。
    
    let regex = /^boon/g;
    let str = "boon, boonful, boondoggle";
    let matches = str.match(regex);
    console.log(matches); // ["boon"]
    
  • $:匹配输入字符串的结束位置。
    
    let regex = /ful$/g;
    let str = "boonful, boon, boondoggle";
    let matches = str.match(regex);
    console.log(matches); // ["ful"]
    
  • \b:匹配单词边界。
    
    let regex = /\bboon\b/g;
    let str = "boonful, boon, boondoggle";
    let matches = str.match(regex);
    console.log(matches); // ["boon"]
    
  • \B:匹配非单词边界。
    
    let regex = /\Bboon\b/g;
    let str = "boonful, boon, boondoggle";
    let matches = str.match(regex);
    console.log(matches); // ["oon", "oon"]
    

4. 分组和引用

-