# 正则

# 1. 基本使用

# 1.1. 基础匹配规则

# 1.1.1. 匹配特定字符或字符串

const regex = /hello/;
const str = "Say hello to the world!";

const matchedIndex = str.search(regex);

console.log( matchedIndex ); //=> 4

# 1.1.2. 匹配任意字符(除了换行符)

const regex = /.+/;
const str = "Any character here!";

const result = str.match(regex);

console.log(result); //=> [ "Any character here!" ]

# 1.1.3. 匹配开始和结束

开始:^

结束:$

const regexOfStart = /^hello/;

const regexOfEnd = /world$/

const str = 'hello world';

console.log(regexOfStart.test(str)); //=> true
console.log(regexOfEnd.test(str)); //=> true

# 1.2. 字符集

# 1.2.1. 匹配指定字符集合

const regex = /[abcde]/;
const str = 'hello world';

const result = str.match(regex);

console.log(result); //=> [ 'e' ]

# 1.2.2. 排除特定字符集合

const regex = /[^abcde]/
const str = 'abcde1';

const result = str.match(regex);

console.log(result); //=> [ '1' ]

# 1.3. 量词

# 1.3.1. 匹配零次或多次(*)

# 2. 替换

# 3. 方法

# 3.1. String.prototype.search(regexp)

说明:

  • 返回第一个匹配的索引

示例:

'abcdefg'.search(/d/); //=> 3

'abcdefg'.search(/x/); //=> -1

参考:

# 3.2. String.prototype.match(regexp)

说明:

  • g,只返回匹配结果
  • 不带 g,会返回分组结果

示例:

const regex_1 = /a(b)(c)/;
const regex_2 = /a(b)(c)/g;
const str = 'abcdefg abcdefg';

console.log( str.match(regex_1) );
// ['abc', 'b', 'c', index: 0, input: 'abcdefg abcdefg', groups: undefined]


console.log( str.match(regex_2) );
// ['abc', 'abc']

参考:

# 3.3. String.prototype.replace(regex | string, string | function)

示例:

// 解析 ${...} 格式的字符串模板

var data = {
  name: '张三',
  age: 18,
};

var strTpl = 'My name is ${name}, ${ age } years old!'
var regex = /\$\{\s*(\w+)\s*}/g;

/**
 * 匹配到才会执行回调函数
 * 回调函数的参数与 match() 方法的返回结果一致
 */
var str = strTpl.replace(regex, (matchedStr, group) => {
  const value = data[group];

  if (value == null) {
    return matchedStr;
  }

  return value;
});

console.log(str); //=> "My name is 张三, 18 years old!"

# 3.4. RegExp.prototype.test(string: string): boolean

注意:

  • g,会记住 lastIndex,导致莫名其妙的错误

# 4. 参考

本章目录