你的位置:首页 > 信息动态 > 新闻中心
信息动态
联系我们

长话简说JavaScript(5)RegExp是什么?

2021/12/12 0:03:03

RegExp 类型支持正则表达式。语法简单

let expression = /pattern/flags;

pattern是任何简单或复杂的正则表达式,包括字符类、限定符、分组、向前查找和反向引用。flags是了表示匹配模式的标记

修饰符含义描述
g全局模式表示查找字符串的全部内容,而不是找到第一个匹配的内容就结束。
i不区分大小写表示在查找匹配时忽略 pattern 和字符串的大小写。
m多行模式表示查找到一行文本末尾时会继续查找。
y粘附模式表示只查找从 lastIndex 开始及之后的字符串。
uUnicode 模式启用 Unicode 匹配。
sdotAll 模式表示元字符.匹配任何字符(包括\n 或\r)。

检测是否设置标记

检测方法说明
global布尔值,表示是否设置了 g 标记。
ignoreCase布尔值,表示是否设置了 i 标记。
unicode布尔值,表示是否设置了 u 标记。
sticky布尔值,表示是否设置了 y 标记。
lastIndex整数,表示在源字符串中下一次搜索的开始位置,始终从 0 开始。
multiline布尔值,表示是否设置了 m 标记。
dotAll布尔值,表示是否设置了 s 标记。
source正则表达式的字面量字符串(不是传给构造函数的模式字符串),没有开头和结尾的斜杠。
flags正则表达式的标记字符串。始终以字面量而非传入构造函数的字符串模式形式返回(没有前后斜杠)。

RegExp 常用方法
RegExp.prototype.exec():在一个指定字符串中执行一个搜索匹配。返回一个结果数组或 null。

const str = 'table football, foosball';
const regex = /foo*/g;
console.log( regex.exec(str)); // foo

RegExp.prototype.test():查看正则表达式与指定的字符串是否匹配。返回 true 或false。

const str = 'table football, foosball';
const regex = /foo*/g;
console.log( regex.test(str)); // true

RegExp.prototype@@match:对正则表达式匹配字符串时,@@match方法用于获取匹配结果。

class RegExp1 extends RegExp {
  [Symbol.match](str) {
    const result = RegExp.prototype[Symbol.match].call(this, str);
    if (result) {
      return 'true';
    }
    return 'false';
  }
}
console.log('2012-07-02'.match(new RegExp1(/dsds/))); // "false"

RegExp.prototype[@@matchAll]:[@@matchAll]方法返回对字符串使用正则表达式的所有匹配项。

class MyRegExp extends RegExp {
  [Symbol.matchAll](str) {
    var result = RegExp.prototype[Symbol.matchAll].call(this, str);
    if (!result) {
      return null;
    } else {
      return Array.from(result);
    }
  }
}
var re = new MyRegExp('([0-9]+)-([0-9]+)-([0-9]+)', 'g');
var str = '2019-01-02|2019-03-07';
var result = str.matchAll(re);
console.log(result); // [ "2016-01-02", "2016", "01", "02" ]

RegExp.prototype@@replace:在一个字符串中用给定的替换器,替换所有符合正则模式的匹配项,并返回替换后的新字符串结果。

class RegExp1 extends RegExp {
  [Symbol.replace](str) {
    return RegExp.prototype[Symbol.replace].call(this, str, '#!@?');
  }
}

console.log('football'.replace(new RegExp1('ball'))); // "foot#!@?"

RegExp.prototype@@search:在给定字符串中的一个搜索以取得匹配正则模式的项,正确返回该正则模式的第一个匹配项的在字符串中的位置索引,错误返回-1

class RegExp1 extends RegExp {
  [Symbol.search](str) {
    return RegExp.prototype[Symbol.search].call(this, str);
  }
}
console.log('football'.search(new RegExp1('ball'))); // 4

RegExp.prototype@@split:通过将给定字符串拆分为子字符串,并返回字符串形成的数组。

class RegExp1 extends RegExp {
  [Symbol.split](str,limit) {
    let result = RegExp.prototype[Symbol.split].call(this, str,limit);
    return result.map( x => "(" + x + ")")
  }
}
console.log('20-09-10'.split(new RegExp1('-'))); //(20),(09),(10)

RegExp.prototype.toString():返回表示指定对象的字符串。

let myExp = new RegExp("a+b+c");
console.log(myExp.toString());       // /a+b+c/

想了解正则表达式该怎么写正则表达式