神秘的元字符
5.什么是元字符?
============
> `* + ? . | {n} {n,} {n,m} ^ $ \b \B [] [^] ()`
**知识点**
1. 量词
2. 边界
3. 集合
4. 分组
5. 优先级
------------------------------------------------------
1.量词
-----
> `* + ? . | {n} {n,} {n,m}`
- `*`: 匹配0次,1次或多次前面的原子
- `+`: 匹配1次或多次前面的原子(至少一次)
- `?`: 匹配0次或1次前面的原子(至多一次)
- `.`: 匹配除换行符之外的任何一个字符
- `|`: 匹配2个或多个分支
- `{n}`: 前面的原子必须出现n次
- `{n,}`: 前面的原子出现不少于n次
- `{n,m}`: 前面原子出现不少于n次, 不超过m次
------------------------------------------------------
2.边界
-----
> `^ $ \b \B`
- `^`: 匹配输入字符串的开始位置的原子
- `$`: 匹配输入字符串的结束位置的原子
- `\b`: 匹配单词的边界
- `\B`: 匹配除单词边界之外的部分
------------------------------------------------------
3.集合
-----
> `[] [^]`
- `[]`: 匹配方括号中的任意一个原子
- `[^]`: 匹配除了方括号中原子之外的任何一个字符
------------------------------------------------------
4.分组
-----
- `()`: 括号内容整体做为一个原子,称为模式单,视为多个单原子组成的大原子
------------------------------------------------------
5.优先级
-------
- 相同级别: 从左到右进行匹配
- 不同级别: 先运算高级别,再运算低级别
|级别| 元字符 | 说明 |
|---|----------------------|--------------|
|1 | \ | 转义字符 |
|2 | () [] | 模式单元/原子表 |
|3 | * + ? {n} {n,} {n,m} | 重复匹配 |
|4 | ^ $ \b \B | 边界 |
|5 | | | 模式选择 |
------------------------------------------------------
### 示例:
```javascript
console.log(
// 量词练习
/ph.p/.exec('php'), //null
/ph.p/.exec('phap'), // ["phap", index: 0, input: "phap", groups: undefined]
/ph*p/.exec('php'), //["php", index: 0, input: "php", groups: undefined]
/ph*p/.exec('pp'), // ["pp", index: 0, input: "pp", groups: undefined]
/ph*p/.exec('phhhhhhp'), //["phhhhhhp", index: 0, input: "phhhhhhp", groups: undefined]
/ph+p/.exec('php'), // ["php", index: 0, input: "php", groups: undefined]
/ph+p/.exec('phhhhhp'), // ["phhhhhp", index: 0, input: "phhhhhp", groups: undefined]
/ph+p/.exec('pp'), // null
/ph?p/.exec('pp'), // ["pp", index: 0, input: "pp", groups: undefined]
/ph?p/.exec('php'), // ["php", index: 0, input: "php", groups: undefined]
/ph?p/.exec('phhp'), // null
// 边界
/^万博manbetx平台/.exec('万博manbetx平台,css,javascript'), // ["万博manbetx平台", index: 0, input: "万博manbetx平台,css,javascript", groups: undefined]
/css/.exec('万博manbetx平台,css,javascript'), // ["css", index: 5, input: "万博manbetx平台,css,javascript", groups: undefined]
/^css/.exec('万博manbetx平台,css,javascript'), // null
/^css/.exec('css,javascript'), // ["css", index: 0, input: "css,javascript", groups: undefined]
// 限制结尾原子也是一样的
/php$/.exec('万博manbetx平台,java,php'), // ["php", index: 10, input: "万博manbetx平台,java,php", groups: undefined]
/php$/.exec('万博manbetx平台,java,php,python'), // null
// 集合之前介绍过了, 下面我们看一下分组
// 分组最常用的场景,就是改变优先级
// 只要以a开头, f结束的字符串,都能匹配到
/^a|f$/.exec('adf'), // ["a", index: 0, input: "adf", groups: undefined]
/^a|f$/.exec('adda12222f'), // ["a", index: 0, input: "adda12222f", groups: undefined]
// 加了括号, 将只能匹配a 或者 f, 其它字符串都不能匹配
/^(a|f)$/.exec('a'), // ["a", "a", index: 0, input: "a", groups: undefined]
/^(a|f)$/.exec('f'), // ["f", "f", index: 0, input: "f", groups: undefined]
/^(a|f)$/.exec('fdd') // null
)
```