JS正则

78 阅读1分钟

MDN 正则表达式

1. 创建正则表达式对象:

使用构造函数:

const regex = new RegExp('pattern', 'flags');

使用字面量:

const regexLiteral = /pattern/flags;

标志

  1. g:全局搜索
  2. i:不区分大小写搜索
  3. m:多行搜索
  4. s:允许 . 匹配换行符
  5. u:使用 unicode 码的模式进行匹配
  6. y:执行 “粘性” 搜索,匹配从目标字符串的当前位置开始

2. 基本匹配:

字符匹配:

const regex = /hello/;
const result = regex.test('hello world');
console.log(result);  // 输出: true

字符集:

const regex = /[aeiou]/;
const result = regex.test('hello');
console.log(result);  // 输出: true

3. 修饰符:

i - 不区分大小写:

const regex = /hello/i;
const result = regex.test('Hello World');
console.log(result);  // 输出: true

g - 全局匹配:

const regex = /hello/g;
const result = 'hello world'.match(regex);
console.log(result);  // 输出: ['hello']

4. 元字符:

. - 任意字符:

const regex = /h.llo/;
const result = regex.test('hello');
console.log(result);  // 输出: true

^ - 开头匹配:

const regex = /^hello/;
const result = regex.test('hello world');
console.log(result);  // 输出: true

$ - 结尾匹配:

const regex = /world$/;
const result = regex.test('hello world');
console.log(result);  // 输出: true

5. 量词:

* - 零次或多次匹配:

const regex = /go*d/;
const result = regex.test('good');
console.log(result);  // 输出: true

+ - 一次或多次匹配:

const regex = /go+d/;
const result = regex.test('good');
console.log(result);  // 输出: true

? - 零次或一次匹配:

const regex = /go?d/;
const result = regex.test('god');
console.log(result);  // 输出: true

6. 分组和捕获:

分组 ( )

const regex = /(\d+)-(\w+)/;
const result = '123-abc'.match(regex);
console.log(result);  // 输出: ['123-abc', '123', 'abc']

7. 特殊字符的转义:

const regex = /a\*b/;
const result = regex.test('a*b');
console.log(result);  // 输出: true

8. 其他常用方法:

test() - 测试字符串是否匹配正则表达式:

const regex = /hello/;
const result = regex.test('hello world');
console.log(result);  // 输出: true

exec() - 查找匹配项,并返回数组:

const regex = /\d+/;
const result = regex.exec('abc 123 xyz');
console.log(result);  // 输出: ['123', index: 4, input: 'abc 123 xyz', groups: undefined]

match() - 在字符串中查找匹配项,并返回数组:

const regex = /\d+/;
const result = 'abc 123 xyz'.match(regex);
console.log(result);  // 输出: ['123']