JS 正则表达式——自学笔记

从大二知道正则表达式,但是一直没有系统的学习过,每次用的时候都是抄百度,今天打算正规的学习一下

1 创建声明一个正则对象

有两种方法可以创建一个 RegExp 对象:一种是字面量,另一种是构造函数

字面量

由斜杠包围而不是引号包围。

构造函数的字符串参数

由引号而不是斜杠包围。

以下三种表达式都会创建相同的正则表达式:

let reg = /ab+c/i;
let reg = new RegExp('ab+c', 'i');
let reg = new RegExp(/ab+c/, 'i');

2 RegExp() 构造函数

/pattern/flags
new RegExp(pattern[, flags])

pattern

flag

如果指定该项,它是一个包含了flag的字符串,可以是以下字符的任意组合。

  • g (global match)
    Find all matches rather than stopping after the first match.
  • i (ignore case)
    If u flag is also enabled, use Unicode case folding.
  • m(multiline)
    Treat beginning and end characters (^ and $) as working over multiple lines. In other words, match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string.
  • s (“dotAll”)
    Allows . to match newlines.
  • u(unicode)
    Treat pattern as a sequence of Unicode code points. (See also Binary strings).
  • y (sticky)
    Matches only from the index indicated by the lastIndex property of this regular expression in the target string. Does not attempt to match from any later indexes.

当指定了 gy 后,RegExp变为有状态,在每次匹配后会设置lastIndex属性,方便后续匹配。

const regex1 = RegExp('foo*', 'g');
const str1 = 'table football, foosball';
let array1;

while ((array1 = regex1.exec(str1)) !== null) {
  console.log(`Found ${array1[0]}. Next starts at ${regex1.lastIndex}.`);
  // expected output: "Found foo. Next starts at 9."
  // expected output: "Found foo. Next starts at 19."
}

3 字符串匹配常用方法

3.1 正则对象方法

RegExp.prototype.test(str): boolean

用于测试字符串参数中是否存在匹配正则表达式模式的字符串

RegExp.prototype.exec(str): Array
使用正则表达式模式对字符串执行搜索,并将更新全局RegExp对象的属性以反映匹配结果。

若没有匹配的文本则返回null,否则返回一个结果数组:

[
  '匹配到的字符串',
  index, // 匹配到的字符串的首位下标
  '输入的字符串',
  groups: undefined
]

3.2 字符串对象方法

在字符串方法中可以使用正则表达式

  1. String.prototype.search()
    用于检测字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串。str.search(reg)返回第一个匹配结果index,没找到返回-1。

  2. String.prototype.match()
    检索字符串,找到一个或多个与regexp匹配的文本,是否具有g对结果影响很大。若无g,那么match方法只能在字符串中执行一次匹配,返回匹配到的字符串或null。有g,返回一个数组,存放匹配到的所有文本的相关信息

  3. String.prototype.replace(reg, replacement)
    replace 方法用 replacement 替换对应的匹配,返回替换后的字符串。replacement 可以是字符串函数,函数的参数是匹配到的字符串,但是不能是箭头函数,因为箭头函数不能取到匹配到的字符串。

reference

4 正则表达式语法 & 常用表达式

练完这篇就会写正则
正则表达式不要背
非常强大的图形化正则表示工具 https://regexper.com/
2020年这些🍔"正则"应该被收藏(更新, 64条)

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值