正则基础

一、基本语法

1.1 字面量创建正则

/a/.test("1111");
// true
/a/.test("1a111");
// false

1.2 对象创建正则

const reg = new RegExp("a", "g");
reg.test("111");
// true
reg.test("aa");
// false

1.3 选择符

// a或者b
/a|b/.test("aaa");
// true

// 138或者139
/138|139/.test("1239999")

// [123456]表示一个字符 1或2或3或4或5或6
/[123456]/.test('1111');

// [1-6]表示一个字符 1或2或3或4或5或6
/[1-6]/.test('1111');

// [abcdefg]表示一个字符 a或b或b或d或e或f或g
/[abcdefg]/.test('bb');

// [a-g]表示一个字符 a或b或b或d或e或f或g
/[a-g]/.test('aaa');

// 原子组12或者34是一个整体
/(12|34)/.test('1234');

1.4 转义

使用字面量正则与对象构造的正则表达式,要注意转义符号

  • "\."普通字符'.' , "."除了换行外的任何字符

  • "d"普通字符'd' ,

  • "\d"匹配一个数字。等价于 [0-9]

  • "\D"匹配一个除了数字的字符,等价于 [^0-9]

  • "w"普通字符'w' , "\w"匹配一个单字字符(字母、数字或者下划线),等价于 [A-Za-z0-9_]

  • "\W"匹配一个单字字符(除了字母、数字或者下划线),等价于[^A-Za-z0-9_]

  • "\s"匹配一个空白字符,包括空格、制表符、换页符和换行符

// .除了换行外的任何字符  \.普通字符

/\d+.\d+/.test(12.35666);

// 匹配网站
/https?:\/\/\w+\.\w+\.\w+/.test("http://www.baidu.com");

1.5 单字符匹配规则

  • 匹配 0 个或者多个(可有可无)
  • 匹配一个或者多个(至少一个)

?匹配 0 个或者一个(至多一个)

// 至多一个s,可以没有s,可以有一个s
/https?/;

1.6 字符边界约束

^起始符:

匹配输入的开始。如果多行标志被设置为 true,那么也匹配换行符后紧跟的位置。

例如,/^A/ 并不会匹配 "an A" 中的 'A',但是会匹配 "An E" 中的 'A'。

当 '^' 作为第一个字符出现在一个字符集合模式时,它将会有不同的含义。

$结束符:

匹配输入的结束。如果多行标志被设置为 true,那么也匹配换行符前的位置。

例如,/t$/ 并不会匹配 "eater" 中的 't',但是会匹配 "eat" 中的 't'。

// 匹配用户名为字母3-6位
/^[a-z]{3,6}$/;

1.7 匹配所有字符

/[\s\S]/

/[\d\D]/

/[\w\W]/

1.8 模式修正符

i 忽略大小写 g 全局匹配 m 多行匹配

// 多行匹配正则
const str = `
  #1  白菜,1.5元 #
  #2  西红柿,2.5元 # 哈哈
 #3  萝卜,3.5元 #
   #4  四季豆,5.5元 #
`;
const result = str.match(/\s*#\d+\s+.+\s+#$/gm).map((item) => {
  const [name, price] = item
    .replace(/\s*#\d+\s*/, "")
    .replace(/\s*#/, "")
    .split(",");
  return { name, price };
});

console.log(result);

/*打印结果:
  [
    { name: '白菜', price: '1.5元' },
    { name: '萝卜', price: '3.5元' },
    { name: '四季豆', price: '5.5元' }
  ]
*/

1.9 原子表

// ([/-]) 后面使用 \1表示后面匹配的字符需要与前面一致
const reg = /^\d{4}([/-])\d{2}\1\d{2}/;

console.log("1997-07-01".match(reg));
// [ '1999-09-07', '-', index: 0, input: '1999-09-07', groups: undefined ]

console.log("1997/07/01".match(reg));
// [ '1999/09/07', '/', index: 0, input: '1999/09/07', groups: undefined ]

console.log("1997/07-01".match(reg));
// null

1.10 排除匹配

// 排除"数字",":","-"
console.log(`张三:010-99999999,李四:020-88888888`.match(/[^\d:\-]+/g));
// 结果为:
// [ '张三', ',李四' ]

2.常用函数

JavaScript 中的正则表达式对象具有一些常用的方法,用于在字符串中进行模式匹配和处理。以下是一些常见的正则表达式方法:

  1. pattern.exec(string):在字符串中查找匹配的模式,并返回第一个匹配项的详细信息,包括匹配的子串、索引位置等。如果没有匹配,返回 null

    const str = "Hello World";
    const pattern = /World/;
    const result = pattern.exec(str);
    console.log(result); // ["World", index: 6, input: "Hello World"]
    

    pattern.exec(str) 方法返回一个数组,包含有关正则表达式匹配的详细信息。如果没有匹配,则返回 null

    返回的数组具有以下属性:

    [0]:数组的第一个元素是匹配的完整子串。 [1]:数组的第二个元素,如果有原子表匹配的。

    index:指示匹配子串在原始字符串中的起始位置的整数值。

    input:包含原始字符串的引用。

    如果没有匹配,exec() 返回 null

    以下是一个示例:

    无原子表

    const str = "Hello World";
    const pattern = /World/;
    const result = pattern.exec(str);
    
    console.log(result[0]); // "World"
    console.log(result.index); // 6
    console.log(result.input); // "Hello World"
    
    const str = "Hello {{World}}";
    const pattern = /\{\{(\S)+\}\}/;
    const result = pattern.exec(str);
    

    一个原子表

    const str = "Hello {{World}}";
    const pattern = /\{\{(\S+)\}\}/;
    const result = pattern.exec(str);
    
    console.log(result[0]); // "{{World}}"
    console.log(result[1]); // "World"
    console.log(result.index); // 6
    console.log(result.input); // "Hello {{World}}"
    

    两个原子表

    const str = "Hello {{World}}";
    const pattern = /(\S+)\s+\{\{(\S+)\}\}/;
    const result = pattern.exec(str);
    
    console.log(result[0]); // "Hello {{World}}"
    console.log(result[1]); // "Hello"
    console.log(result[2]); // "World"
    console.log(result.index); // 0
    console.log(result.input); // "Hello {{World}}"
    

在这个示例中,正则表达式 /World/ 匹配了字符串 "Hello World" 中的 "World"exec() 返回一个包含匹配信息的数组。

  1. pattern.test(string):检查字符串中是否存在与正则表达式匹配的子串,并返回布尔值 truefalse

    const str = "Hello World";
    const pattern = /World/;
    const isMatched = pattern.test(str);
    console.log(isMatched); // true
    
  2. string.match(pattern):在字符串中查找匹配的模式,并返回所有匹配项的数组。如果没有匹配,返回 null

    const str = "Hello World, Hello Universe";
    const pattern = /Hello/g;
    const result = str.match(pattern);
    console.log(result); // ["Hello", "Hello"]
    
  3. string.search(pattern):在字符串中搜索匹配的模式,并返回第一个匹配项的索引位置。如果没有匹配,返回 -1

    const str = "Hello World";
    const pattern = /World/;
    const index = str.search(pattern);
    console.log(index); // 6
    
  4. string.replace(pattern,replacement):在字符串中搜索匹配的模式,并将其替换为指定的字符串。返回替换后的新字符串。

    const str = "Hello World";
    const pattern = /World/;
    const replacement = "Universe";
    const newStr = str.replace(pattern, replacement);
    console.log(newStr); // "Hello Universe"
    
  5. string.split(pattern):将字符串分割成数组,使用正则表达式作为分隔符。

    const str = "apple,banana,kiwi";
    const pattern = /,/;
    const result = str.split(pattern);
    console.log(result); // ["apple", "banana", "kiwi"]
    

这些是正则表达式对象的一些常用方法,它们可以帮助你在字符串中进行模式匹配、替换和分割等操作。根据你的需求,选择适当的方法来处理字符串中的正则表达式匹配。

Contributors: masecho