常用Regex和JS可以使用Regex 处理字符串的API 小抄

93 阅读1分钟

常用的基础Regex符号

*   .  -- any character except new line(除了换行符的任意一个字符)
*   \d -- digit(数字0-9)
*   \D -- not a digit (非数字)
*   \w -- word caracter (单词字符包括 a-z A-Z 0-9 _)
*   \W -- not a word caracter (非单词字符,比如说特殊字符空白字符 white space special sign, not a _)
*   \s -- whitespace (空白空间字符 比如空格 tab或者换行字符 space tab newline)
*   \S -- not white space (非空白字符)
*   
*   \b -- word boundary (单词边界)
*   \B -- not word boundary (非单词边界)
*   ^  -- begin of string (字符串的开头符)
*   \$  -- end of a string (字符串的结尾符)
*
*   \[] -- match one the letter inside (匹配一个在中括号里面的字符)
*   \[^] -- not match (不匹配某个字符)
*   |   -- or (或者)
*   () --group (群符号 例如 M(r|rs|s)) 
*
*   * -- 0 or more(零个以上含零个)
*   + -- one or more (一个以上含一个)
*   ? -- 0 or one (一个或者零个)
*   {3} -- exact number (三个)
*   {3,4} -- range: 3 to 4 (三到四个)
*.  {3,} -- range: 3 to illimite (三个以上含三个)
*
*   \n -- matches the same text as most recently matched by the Nth capturing group (最近群符号匹配的内容重新出现)

具体的简单例子

  const lowerLetter = /a-z/g; //所有小写
  const upperLetter = /A-Z/g; //所有大写
  const digit = /\d/g;    //所有数字0-9
  const special = /[^\d\s]/; //非数字非空格
  const repeat = /(.{3,})\1([c|d])\2/  
  //(.{3,})第一组,匹配至少三个数字,
  //([c|d])第二组匹配c或者d,
  // \1 第一组匹配的重复一次
  // \2 第二组匹配的重复一次
  
  
  const str = "abcabcdd";
  repeat3.test(str) ->true 
  //第一组匹配abc重复一次,第二组匹配d重复一次
  

常用的可以使用Regex的JS API

/**
 * - string.search()
 * - string.replace()
 * - string.replaceAll()
 * - string.match()
     注意点:如果有匹配到返回一个数组,但是如果没有匹配到返回的是NULL
 * - string.matchAll()
 * - RegExp.test(string) 
     例子: 
     const regex = /a/g (或者 const regex=new Regex('a',g));
     regex.test("abc");
 */

关于Regex的奇异行为

在使用 RegExp.test(string)这种形式的判断的时候,如果和 "g" 一起使用 会有一些奇怪的行为。例如下面的例子test会交替返回true和false。这种行为的原因可以参考MDN链接

// 匹配以A S W D四个大写开头 然后紧接着匹配一位到两位数字 例子 A2 W10 S5 D01 都可以成功匹配
const regex = /^[ASWD]{1}\d{1,2}$/g  

console.log(regex.test("A20"))  // --> true
console.log(regex.lastIndex)  // --> 3
console.log(regex.test("A20"))  // --> false   
//返回false的原因: 由于用 "g"flag,会从上次lastIndex的位置开始搜索。上一次搜索都 位置 3,从位置3 开始搜索没有可以匹配A20的了。所以返回false
console.log(regex.test("A20"))  // --> true
console.log(regex.test("A20"))  // --> false