# 什么是正则表达式

正则表达式是一种文本模式，包括普通字符（如a 到 z 之间的字母）和特殊字符（元字符）

维基百科定义：

> 正则表达式（英语：Regular Expression，在代码中常简写为regex、regexp或RE），又称正则表示式、正则表示法、规则表达式、常规表示法，是计算机科学的一个概念

## 正则语言

正则表达式匹配字符串的能力等价于有穷状态自动机。它能匹配出的语言都是正则语言

维基百科描述：

> 正则语言又称正规语言是满足下述相互等价的一组条件的一类形式语言：
>
> * 可以被确定有限状态自动机识别
> * 可以被非确定有限状态自动机识别
> * 可以被只读图灵机识别
> * 可以用正则表达式描述
> * 可以用正则文法生成
> * 可以用前缀文法生成

计算理论中语言定义：

> 如果 `A` 是机器 `M` 所接受的所有字符串组成的集合,那么我们就说 `A` 是 机器 `M` 的语言，也可以写作 L(M)=A 或者 M 识别 A

## 正则表达式用途

### 测试字符串

* 表单验证，校验输入文本的合法性，如：符合电话号码/邮箱格式等
* Api入参验证，校验调用接口传入参数的合法性，如：int/string类型等

```javascript
// 校验是否是纯数字
/^[\d]+$/.test('100'); // true

/^[\d]+$/.test(100); // true

/^[\d]+$/.test('abc100'); // fals
```

### 替换文本

* 替换，快速替换文本中某些格式字符串为其他文本内容
* 删除，快速批量删除文本中出现的某些字符串

```javascript
// 把“-”替换为“@”
'nxtech-regexp'.replace(/\-/g, '@'); // nxtech@regexp

// 删除字符串中的空格
'一 起 学 RegExp'.replace(/\s/g, ''); // "一起学RegExp"
```

### 从字符串中提取子字符串

* 从字符串中提取指定格式的子字符串
* 从url中提取路由参数，查询参数等

```javascript
// 从字符串提取纯数字字符串 
'abc123abc'.match(/[0-9]+/); // 123

// 从url中提取查询参数，下述从qq地址中提取参数参数name的值
'http://www.qq.com?name=qq'.match(/(?:\?|&)name=([^&]*)/); // [0: '?name=qq', 1: 'qq', ...]
```

##


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://nxtech.gitbook.io/regexp/introduction/what-is-a-regexp.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
