# 正则表达式

* [正则练习](http://www.52cik.com/regex-tuesday/)

## 1.生成一个正则表达式regexObj

* 描述字符串规则的表达式，两种方式
  * 直接量： `/pattren/attrs`(/规则/属性)
  * 对象构造方式：`new RegExp(pattern,arrtes)` (/规则/属性)

## 2.regexObj.test(str)

* 测试正则表达式regexObj与指定字符串是否匹配

```javascript
/10086/.test('10086') //true
/10086/.test('12314') //false
/10086/.test('x10086s') //true //true
```

* 由此看到`.test()`匹配了正则表达式，但是最后一条出来了一个问题。如果这种情况下`/10086/.test('x10086s')`正则表达式匹配到该字符串中确实含有此正则表达式
* 所以必须要有一些限制，以下就是限制方法

### 锚点

* 我们可以通过一个锚点匹配一个位置
  * `^`：起始位置
  * `$` ：结尾位置
  * `\b` ：单词边界

```javascript
//起始位置
/^http:/.test('http://www.kejiganhuo.com') // true 以http:为起始的字符串可以匹配
/^http:/.test('attp://www.kejiganhuo.com') // false
/^http:/.test('https://www.kejiganhuo.com') //false
//结尾位置
/\.jpg$/.test('1.jpg') // true 以.jsp结尾的字符串可以匹配
/\.jsp$/.test('1.jpg ls') // false
//单词边界
/\bis\b/.test('this is tyrmars') // true 这里is才是正则所匹配的，匹配的就是is，就是看有没有is字符串
/\bis\b/.test('this') // false this是无法匹配单词边界为is
/is\b/.test('this tyrmars') // true 这样就可以匹配，因为单词左边界没有限制
```

#### example1

```javascript
/^10086$/.test('10086') //true
```

* 这种方法只能检测固定的号码，但是我们想检测同类的手机号码，所以就需要用到如下 **字符类**

### 字符类

* 匹配一类字符中的一个，采用`[]`，相当于限定字符集
  * `[abc]`：a或b或c
  * `[0-9]`：一个数字
  * `[^0-9]`：非数字的一个字符
  * `[a-z]`：一个字母
  * `.`：任意一个字符(除还行外)

```javascript
/[0-9]/.test(123) // true
/[^1-9]/.test(0123) // false
/[12345]/.test(0) // false
/[abc]/.test('abcdefgh') //true
/[abc]/.test('fgh') //false
```

#### example2

```javascript
/^1[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]$/.test(12345678901) //true
```

* `[0-9]`可以被优化，所以学习到了元字符，元字符是具有特殊意义的字符

### 元字符

* 具有特殊意义的字符
  * `^`、`$`、`\b`&#x20;
  * `\d`：`[0-9]`
  * `\D`：`[^\d]`
  * `\s`：空白符
  * `\S`：`[^\s]`
  * `\w`：`[A-Z]`
  * `\W`：`[^\w]`

#### example3

```javascript
/^1\d\d\d\d\d\d\d\d\d\d\d$/.test(12345678901) //true
```

* 不过呢，想一下这些`\d`都是重复的，所以需要用到量词

### 量词

* 出现的次数
  * `{m,n}`：m到n次
  * `*`：`{0,}` 出现0或n次
  * `?`：`{0,1}` 出现0或者1次
  * `+`：`{1,}` 出现1或n次


---

# 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://jonathan-zhang.gitbook.io/javascript-steppitguide/ji-chu-zhi-shi/15.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.
