一、基础概念

1.1 什么是 .test() 方法?

.test() 是 JavaScript 正则表达式对象的内置方法,用于测试字符串是否匹配正则表达式模式。

语法:

regexObj.test(str)

参数:

  • str:要测试的字符串

返回值:

  • true:字符串匹配正则表达式
  • false:字符串不匹配正则表达式

1.2 正则表达式的创建方式

// 方式1:字面量(推荐)
const regex1 = /pattern/flags;
const regex2 = /abc/;
const regex3 = /abc/gi;

// 方式2:构造函数
const regex4 = new RegExp('pattern', 'flags');
const regex5 = new RegExp('abc');
const regex6 = new RegExp('abc', 'gi');

// 错误示例
const wrong1 = abc;      // 错误:abc是未定义变量
const wrong2 = 'abc';    // 错误:这是字符串,不是正则
// wrong2.test('abc');   // TypeError: wrong2.test is not a function

二、基本用法示例

2.1 简单匹配

const regex = /hello/;

console.log(regex.test('hello world'));    // true
console.log(regex.test('Hello world'));    // false(区分大小写)
console.log(regex.test('say hello'));      // true
console.log(regex.test('hi world'));       // false

2.2 使用标志(flags)

// i - 忽略大小写
const regex1 = /hello/i;
console.log(regex1.test('Hello'));         // true
console.log(regex1.test('HELLO'));         // true

// g - 全局匹配(对test()影响不大)
const regex2 = /a/g;
console.log(regex2.test('banana'));        // true

// m - 多行匹配
const regex3 = /^hello/m;
console.log(regex3.test('world\nhello'));  // true

三、粘性标志 y(Sticky Flag)

3.1 什么是粘性匹配?

粘性标志 y 使正则表达式在指定位置(lastIndex)进行匹配,不会在字符串中搜索。

在整个字符串搜索
只在lastIndex位置
找到cc
位置0是w
普通匹配 /cc/
wwwwccwww
粘性匹配 /cc/y
wwwwccwww
返回true
返回false

3.2 粘性匹配示例

const str = 'aaabbbccc';

// 普通匹配
const normal = /bbb/;
console.log(normal.test(str));        // true(在任意位置找到bbb)

// 粘性匹配
const sticky = /bbb/y;
console.log(sticky.test(str));        // false(位置0不是bbb)

// 设置lastIndex
sticky.lastIndex = 3;
console.log(sticky.test(str));        // true(位置3正好是bbb)
console.log(sticky.lastIndex);        // 6(匹配后自动更新)

3.3 粘性匹配工作流程

匹配成功
匹配失败
开始匹配
检查lastIndex位置
返回true
返回false
更新lastIndex
重置lastIndex为0

四、实际应用案例

4.1 验证邮箱格式

const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

console.log(emailRegex.test('user@example.com'));    // true
console.log(emailRegex.test('invalid.email'));       // false
console.log(emailRegex.test('user@sub.example.com')); // true

4.2 检查密码强度

// 至少8位,包含大小写字母和数字
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;

console.log(passwordRegex.test('Pass123word'));      // true
console.log(passwordRegex.test('password123'));      // false(无大写)
console.log(passwordRegex.test('PASSWORD123'));      // false(无小写)
console.log(passwordRegex.test('Password'));         // false(无数字)

4.3 使用粘性标志解析Token

const tokens = 'abc:123:def:456';
const tokenRegex = /(\w+):?/y;
const results = [];

while (tokenRegex.lastIndex < tokens.length) {
    const match = tokenRegex.exec(tokens);
    if (match) {
        results.push(match[1]);
    } else {
        break;
    }
}

console.log(results); // ['abc', '123', 'def', '456']

五、性能考虑

5.1 正则表达式缓存

// 好的做法:缓存正则表达式
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

function validateEmail(email) {
    return EMAIL_REGEX.test(email);
}

// 避免:每次创建新的正则表达式
function validateEmailBad(email) {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

5.2 标志对比

正则表达式标志
无标志
i - 忽略大小写
g - 全局匹配
m - 多行匹配
y - 粘性匹配
默认行为
大小写不敏感
查找所有匹配
^和$匹配行首尾
从lastIndex位置匹配
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐