Skip to content

第五章 正则表达式的拆分 有一个正则小问题 #6

@qianlongo

Description

@qianlongo

问题位置

第五章 正则表达式的拆分 5.2.2 量词连缀问题

原文描述

假设,要匹配这样的字符串:

  1. 每个字符为 "a、"b"、"c" 任选其一,
  2. 字符串的长度是 3 的倍数

此时正则不能想当然地写成 /^[abc]{3}+$/,这样会报错,说 + 前面没什么可重复的:此时要修改成: /([abc]{3})+/

疑问点

/([abc]{3})+/.test('abcx')  // 为true 不能保证所有的字符串都是abc之一
/([abc]{3})+/.test('abcc') // 为true 不能保证长度是3的倍数

所以写成
/^([abc]{3})+$/.test('abcabc')

就可以保证,

  1. 每个字符为 "a、"b"、"c" 任选其一
  2. 字符串的长度是 3 的倍数

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions