Merge remote-tracking branch 'zeeshanu/master'

# Conflicts:
#	README.md
This commit is contained in:
GrayLand 2017-08-15 09:20:03 +08:00
commit 381dcc986e
3 changed files with 1060 additions and 18 deletions

493
README-cn.md Normal file
View File

@ -0,0 +1,493 @@
<br/>
<p align="center">
<img src="https://i.imgur.com/bYwl7Vf.png" alt="Learn Regex">
</p><br/>
## 翻译:
* [English](README.md)
* [中文版](README-cn.md)
## 什么是正则表达式?
> 正则表达式是一组由字母和符号组成的特殊文本, 它可以用来从文本中找出满足你想要的格式的句子.
一个正则表达式是在一个主体字符串中从左到右匹配字符串时的一种样式.
例如"Regular expression"是一个完整的句子, 但我们常使用缩写的术语"regex"或"regexp".
正则表达式可以用来替换文本中的字符串,验证形式,提取字符串等等.
想象你正在写一个应用, 然后你想设定一个用户命名的规则, 让用户名包含字符,数字,下划线和连字符,以及限制字符的个数,好让名字看起来没那么丑.
我们使用以下正则表达式来验证一个用户名:
<br/><br/>
<p align="center">
<img src="https://i.imgur.com/Pq5Llat.png" alt="Regular expression">
</p>
以上的正则表达式可以接受 `john_doe`, `jo-hn_doe`, `john12_as`.
但不匹配`Jo`, 因为它包含了大写的字母而且太短了.
目录
=================
* [1. 基本匹配](#1-基本匹配)
* [2. 元字符](#2-元字符)
* [2.1 点运算符 .](#21-点运算符-)
* [2.2 字符集](#22-字符集)
* [2.2.1 否定字符集](#221-否定字符集)
* [2.3 重复次数](#23-重复次数)
* [2.3.1 * 号](#231--号)
* [2.3.2 号](#232--号)
* [2.3.3 ? 号](#233--号)
* [2.4 {} 号](#24--号)
* [2.5 (...) 特征标群](#25--特征标群)
* [2.6 | 或运算符](#26--或运算符)
* [2.7 转码特殊字符](#27-转码特殊字符)
* [2.8 锚点](#28-锚点)
* [2.8.1 ^ 号](#281--号)
* [2.8.2 $ 号](#282--号)
* [3. 简写字符集](#3-简写字符集)
* [4. 前后关联约束(前后预查)](#4-前后关联约束前后预查)
* [4.1 ?=... 前置约束(存在)](#41--前置约束存在)
* [4.2 ?!... 前置约束-排除](#42--前置约束-排除)
* [4.3 ?&lt;= ... 后置约束-存在](#43---后置约束-存在)
* [4.4 ?&lt;!... 后置约束-排除](#44--后置约束-排除)
* [5. 标志](#5-标志)
* [5.1 忽略大小写 (Case Insensitive)](#51-忽略大小写-case-insensitive)
* [5.2 全局搜索 (Global search)](#52-全局搜索-global-search)
* [5.3 多行修饰符 (Multiline)](#53-多行修饰符-multiline)
* [额外补充](#额外补充)
* [贡献](#贡献)
* [许可证](#许可证)
## 1. 基本匹配
正则表达式其实就是在执行搜索时的格式, 它由一些字母和数字组合而成.
例如: 一个正则表达式 `the`, 它表示一个规则: 由字母`t`开始,接着是`h`,再接着是`e`.
<pre>
"the" => The fat cat sat on <a href="#learn-regex"><strong>the</strong></a> mat.
</pre>
[在线练习](https://regex101.com/r/dmRygT/1)
正则表达式`123`匹配字符串`123`. 它逐个字符的与输入的正则表达式做比较.
正则表达式是大小写敏感的, 所以`The`不会匹配`the`.
<pre>
"The" => <a href="#learn-regex"><strong>The</strong></a> fat cat sat on the mat.
</pre>
[在线练习](https://regex101.com/r/1paXsy/1)
## 2. 元字符
正则表达式主要依赖于元字符.
元字符不代表他们本身的字面意思, 他们都有特殊的含义. 一些元字符写在方括号中的时候有一些特殊的意思. 以下是一些元字符的介绍:
|元字符|描述|
|:----:|----|
|.|句号匹配任意单个字符除了换行符.|
|[ ]|字符种类. 匹配方括号内的任意字符.|
|[^ ]|否定的字符种类. 匹配除了方括号里的任意字符|
|*|匹配>=0个重复的在*号之前的字符.|
|+|匹配>=1个重复的+号前的字符.
|?|标记?之前的字符为可选.|
|{n,m}|匹配num个中括号之前的字符 (n <= num <= m).|
|(xyz)|字符集, 匹配与 xyz 完全相等的字符串.|
|&#124;|或运算符,匹配符号前或后的字符.|
|&#92;|转义字符,用于匹配一些保留的字符 <code>[ ] ( ) { } . * + ? ^ $ \ &#124;</code>|
|^|从开始行开始匹配.|
|$|从末端开始匹配.|
## 2.1 点运算符 `.`
`.`是元字符中最简单的例子.
`.`匹配任意单个字符, 但不匹配换行符.
例如, 表达式`.ar`匹配一个任意字符后面跟着是`a``r`的字符串.
<pre>
".ar" => The <a href="#learn-regex"><strong>car</strong></a> <a href="#learn-regex"><strong>par</strong></a>ked in the <a href="#learn-regex"><strong>gar</strong></a>age.
</pre>
[在线练习](https://regex101.com/r/xc9GkU/1)
## 2.2 字符集
字符集也叫做字符类.
方括号用来指定一个字符集.
在方括号中使用连字符来指定字符集的范围.
在方括号中的字符集不关心顺序.
例如, 表达式`[Tt]he` 匹配 `the``The`.
<pre>
"[Tt]he" => <a href="#learn-regex"><strong>The</strong></a> car parked in <a href="#learn-regex"><strong>the</strong></a> garage.
</pre>
[在线练习](https://regex101.com/r/2ITLQ4/1)
方括号的句号就表示句号.
表达式 `ar[.]` 匹配 `ar.`字符串
<pre>
"ar[.]" => A garage is a good place to park a c<a href="#learn-regex"><strong>ar.</strong></a>
</pre>
[在线练习](https://regex101.com/r/wL3xtE/1)
### 2.2.1 否定字符集
一般来说 `^` 表示一个字符串的开头, 但它用在一个方括号的开头的时候, 它表示这个字符集是否定的.
例如, 表达式`[^c]ar` 匹配一个后面跟着`ar`的除了`c`的任意字符.
<pre>
"[^c]ar" => The car <a href="#learn-regex"><strong>par</strong></a>ked in the <a href="#learn-regex"><strong>gar</strong></a>age.
</pre>
[在线练习](https://regex101.com/r/nNNlq3/1)
## 2.3 重复次数
后面跟着元字符 `+`, `*` or `?` 的, 用来指定匹配子模式的次数.
这些元字符在不同的情况下有着不同的意思.
### 2.3.1 `*`
`*`号匹配 在`*`之前的字符出现`大于等于0`次.
例如, 表达式 `a*` 匹配以0或更多个a开头的字符, 因为有0个这个条件, 其实也就匹配了所有的字符. 表达式`[a-z]*` 匹配一个行中所有以小写字母开头的字符串.
<pre>
"[a-z]*" => T<a href="#learn-regex"><strong>he</strong></a> <a href="#learn-regex"><strong>car</strong></a> <a href="#learn-regex"><strong>parked</strong></a> <a href="#learn-regex"><strong>in</strong></a> <a href="#learn-regex"><strong>the</strong></a> <a href="#learn-regex"><strong>garage</strong></a> #21.
</pre>
[在线练习](https://regex101.com/r/7m8me5/1)
`*`字符和`.`字符搭配可以匹配所有的字符`.*`.
`*`和表示匹配空格的符号`\s`连起来用, 如表达式`\s*cat\s*`匹配0或更多个空格开头和0或更多个空格结尾的cat字符串.
<pre>
"\s*cat\s*" => The fat<a href="#learn-regex"><strong> cat </strong></a>sat on the <a href="#learn-regex">con<strong>cat</strong>enation</a>.
</pre>
[在线练习](https://regex101.com/r/gGrwuz/1)
### 2.3.2 `+`
`+`号匹配`+`号之前的字符出现 >=1 次个字符.
例如表达式`c.+t` 匹配以首字母`c`开头以`t`结尾,中间跟着任意个字符的字符串.
<pre>
"c.+t" => The fat <a href="#learn-regex"><strong>cat sat on the mat</strong></a>.
</pre>
[在线练习](https://regex101.com/r/Dzf9Aa/1)
### 2.3.3 `?`
在正则表达式中元字符 `?` 标记在符号前面的字符为可选, 即出现 0 或 1 次.
例如, 表达式 `[T]?he` 匹配字符串 `he``The`.
<pre>
"[T]he" => <a href="#learn-regex"><strong>The</strong></a> car is parked in the garage.
</pre>
[在线练习](https://regex101.com/r/cIg9zm/1)
<pre>
"[T]?he" => <a href="#learn-regex"><strong>The</strong></a> car is parked in t<a href="#learn-regex"><strong>he</strong></a> garage.
</pre>
[在线练习](https://regex101.com/r/kPpO2x/1)
## 2.4 `{}`
在正则表达式中 `{}` 是一个量词, 常用来一个或一组字符可以重复出现的次数.
例如, 表达式 `[0-9]{2,3}` 匹配 2~3 位 0~9 的数字.
<pre>
"[0-9]{2,3}" => The number was 9.<a href="#learn-regex"><strong>999</strong></a>7 but we rounded it off to <a href="#learn-regex"><strong>10</strong></a>.0.
</pre>
[在线练习](https://regex101.com/r/juM86s/1)
我们可以省略第二个参数.
例如, `[0-9]{2,}` 匹配至少两位 0~9 的数字.
如果逗号也省略掉则表示重复固定的次数.
例如, `[0-9]{3}` 匹配3位数字
<pre>
"[0-9]{2,}" => The number was 9.<a href="#learn-regex"><strong>9997</strong></a> but we rounded it off to <a href="#learn-regex"><strong>10</strong></a>.0.
</pre>
[在线练习](https://regex101.com/r/Gdy4w5/1)
<pre>
"[0-9]{3}" => The number was 9.<a href="#learn-regex"><strong>999</strong></a>7 but we rounded it off to 10.0.
</pre>
[在线练习](https://regex101.com/r/Sivu30/1)
## 2.5 `(...)` 特征标群
特征标群是一组写在 `(...)` 中的子模式. 例如之前说的 `{}` 是用来表示前面一个字符出现指定次数. 但如果在 `{}` 前加入特征标群则表示整个标群内的字符重复 N 次. 例如, 表达式 `(ab)*` 匹配连续出现 0 或更多个 `ab`.
我们还可以在 `()` 中用或字符 `|` 表示或. 例如, `(c|g|p)ar` 匹配 `car``gar``par`.
<pre>
"(c|g|p)ar" => The <a href="#learn-regex"><strong>car</strong></a> is <a href="#learn-regex"><strong>par</strong></a>ked in the <a href="#learn-regex"><strong>gar</strong></a>age.
</pre>
[在线练习](https://regex101.com/r/tUxrBG/1)
## 2.6 `|` 或运算符
或运算符就表示或, 用作判断条件.
例如 `(T|t)he|car` 匹配 `(T|t)he``car`.
<pre>
"(T|t)he|car" => <a href="#learn-regex"><strong>The</strong></a> <a href="#learn-regex"><strong>car</strong></a> is parked in <a href="#learn-regex"><strong>the</strong></a> garage.
</pre>
[在线练习](https://regex101.com/r/fBXyX0/1)
## 2.7 转码特殊字符
反斜线 `\` 在表达式中用于转码紧跟其后的字符. 用于指定 `{ } [ ] / \ + * . $ ^ | ?` 这些特殊字符. 如果想要匹配这些特殊字符则要在其前面加上反斜线 `\`.
例如 `.` 是用来匹配除换行符外的所有字符的. 如果想要匹配句子中的 `.` 则要写成 `\.`.
<pre>
"(f|c|m)at\.?" => The <a href="#learn-regex"><strong>fat</strong></a> <a href="#learn-regex"><strong>cat</strong></a> sat on the <a href="#learn-regex"><strong>mat.</strong></a>
</pre>
[在线练习](https://regex101.com/r/DOc5Nu/1)
## 2.8 锚点
在正则表达式中, 想要匹配指定开头或结尾的字符串就要使用到锚点. `^` 指定开头, `$` 指定结尾.
### 2.8.1 `^`
`^` 用来检查匹配的字符串是否在所匹配字符串的开头.
例如, 在 `abc` 中使用表达式 `^a` 会得到结果 `a`. 但如果使用 `^b` 将匹配不到任何结果. 应为在字符串 `abc` 中并不是以 `b` 开头.
例如, `^(T|t)he` 匹配以 `The``the` 开头的字符串.
<pre>
"(T|t)he" => <a href="#learn-regex"><strong>The</strong></a> car is parked in <a href="#learn-regex"><strong>the</strong></a> garage.
</pre>
[在线练习](https://regex101.com/r/5ljjgB/1)
<pre>
"^(T|t)he" => <a href="#learn-regex"><strong>The</strong></a> car is parked in the garage.
</pre>
[在线练习](https://regex101.com/r/jXrKne/1)
### 2.8.2 `$`
同理于 `^` 号, `$` 号用来匹配字符是否是最后一个.
例如, `(at\.)$` 匹配以 `at.` 结尾的字符串.
<pre>
"(at\.)" => The fat c<a href="#learn-regex"><strong>at.</strong></a> s<a href="#learn-regex"><strong>at.</strong></a> on the m<a href="#learn-regex"><strong>at.</strong></a>
</pre>
[在线练习](https://regex101.com/r/y4Au4D/1)
<pre>
"(at\.)$" => The fat cat. sat. on the m<a href="#learn-regex"><strong>at.</strong></a>
</pre>
[在线练习](https://regex101.com/r/t0AkOd/1)
## 3. 简写字符集
正则表达式提供一些常用的字符集简写. 如下:
|简写|描述|
|:----:|----|
|.|除换行符外的所有字符|
|\w|匹配所有字母数字, 等同于 `[a-zA-Z0-9_]`|
|\W|匹配所有非字母数字, 即符号, 等同于: `[^\w]`|
|\d|匹配数字: `[0-9]`|
|\D|匹配非数字: `[^\d]`|
|\s|匹配所有空格字符, 等同于: `[\t\n\f\r\p{Z}]`|
|\S|匹配所有非空格字符: `[^\s]`|
## 4. 前后关联约束(前后预查)
前置约束和后置约束都属于**非捕获簇**(用于匹配不在匹配列表中的格式).
前置约束用于判断所匹配的格式是否在另一个确定的格式之后.
例如, 我们想要获得所有跟在 `$` 符号后的数字, 我们可以使用正向向后约束 `(?<=\$)[0-9\.]*`.
这个表达式匹配 `$` 开头, 之后跟着 `0,1,2,3,4,5,6,7,8,9,.` 这些字符可以出现大于等于 0 次.
前后关联约束如下:
|符号|描述|
|:----:|----|
|?=|前置约束-存在|
|?!|前置约束-排除|
|?<=|后置约束-存在|
|?<!|后置约束-排除|
### 4.1 `?=...` 前置约束(存在)
`?=...` 前置约束(存在), 表示第一部分表达式必须跟在 `?=...`定义的表达式之后.
返回结果只瞒住第一部分表达式.
定义一个前置约束(存在)要使用 `()`. 在括号内部使用一个问号和等号: `(?=...)`.
前置约束的内容写在括号中的等号后面.
例如, 表达式 `[T|t]he(?=\sfat)` 匹配 `The``the`, 在括号中我们又定义了前置约束(存在) `(?=\sfat)` ,即 `The``the` 后面紧跟着 `(空格)fat`.
<pre>
"[T|t]he(?=\sfat)" => <a href="#learn-regex"><strong>The</strong></a> fat cat sat on the mat.
</pre>
[在线练习](https://regex101.com/r/IDDARt/1)
### 4.2 `?!...` 前置约束-排除
前置约束-排除 `?!` 用于筛选所有匹配结果, 筛选条件为 其后不跟随着定义的格式
`前置约束-排除` 定义和 `前置约束(存在)` 一样, 区别就是 `=` 替换成 `!` 也就是 `(?!...)`.
表达式 `[T|t]he(?!\sfat)` 匹配 `The``the`, 且其后不跟着 `(空格)fat`.
<pre>
"[T|t]he(?!\sfat)" => The fat cat sat on <a href="#learn-regex"><strong>the</strong></a> mat.
</pre>
[在线练习](https://regex101.com/r/V32Npg/1)
### 4.3 `?<= ...` 后置约束-存在
后置约束-存在 记作`(?<=...)` 用于筛选所有匹配结果, 筛选条件为 其前跟随着定义的格式.
例如, 表达式 `(?<=[T|t]he\s)(fat|mat)` 匹配 `fat``mat`, 且其前跟着 `The``the`.
<pre>
"(?<=[T|t]he\s)(fat|mat)" => The <a href="#learn-regex"><strong>fat</strong></a> cat sat on the <a href="#learn-regex"><strong>mat</strong></a>.
</pre>
[在线练习](https://regex101.com/r/avH165/1)
### 4.4 `?<!...` 后置约束-排除
后置约束-排除 记作 `(?<!...)` 用于筛选所有匹配结果, 筛选条件为 其前不跟着定义的格式.
例如, 表达式 `(?<!(T|t)he\s)(cat)` 匹配 `cat`, 且其前不跟着 `The``the`.
<pre>
"(?&lt;![T|t]he\s)(cat)" => The cat sat on <a href="#learn-regex"><strong>cat</strong></a>.
</pre>
[在线练习](https://regex101.com/r/8Efx5G/1)
## 5. 标志
标志也叫修饰语, 因为它可以用来修改表达式的搜索结果.
这些标志可以任意的组合使用, 它也是整个正则表达式的一部分.
|标志|描述|
|:----:|----|
|i|忽略大小写.|
|g|全局搜索.|
|m|多行的: 锚点元字符 `^` `$` 工作范围在每行的起始.|
### 5.1 忽略大小写 (Case Insensitive)
修饰语 `i` 用于忽略大小写.
例如, 表达式 `/The/gi` 表示在全局搜索 `The`, 在后面的 `i` 将其条件修改为忽略大小写, 则变成搜索 `the``The`, `g` 表示全局搜索.
<pre>
"The" => <a href="#learn-regex"><strong>The</strong></a> fat cat sat on the mat.
</pre>
[在线练习](https://regex101.com/r/dpQyf9/1)
<pre>
"/The/gi" => <a href="#learn-regex"><strong>The</strong></a> fat cat sat on <a href="#learn-regex"><strong>the</strong></a> mat.
</pre>
[在线练习](https://regex101.com/r/ahfiuh/1)
### 5.2 全局搜索 (Global search)
修饰符 `g` 常用语执行一个全局搜索匹配, 即(不仅仅返回第一个匹配的, 而是返回全部).
例如, 表达式 `/.(at)/g` 表示搜索 任意字符(除了换行) + `at`, 并返回全部结果.
<pre>
"/.(at)/" => The <a href="#learn-regex"><strong>fat</strong></a> cat sat on the mat.
</pre>
[在线练习](https://regex101.com/r/jnk6gM/1)
<pre>
"/.(at)/g" => The <a href="#learn-regex"><strong>fat</strong></a> <a href="#learn-regex"><strong>cat</strong></a> <a href="#learn-regex"><strong>sat</strong></a> on the <a href="#learn-regex"><strong>mat</strong></a>.
</pre>
[在线练习](https://regex101.com/r/dO1nef/1)
### 5.3 多行修饰符 (Multiline)
多行修饰符 `m` 常用语执行一个多行匹配.
像之前介绍的 `(^,$)` 用于检查格式是否是在待检测字符串的开头或结尾. 但我们如果想要它在每行的开头和结尾生效, 我们需要用到多行修饰符 `m`.
例如, 表达式 `/at(.)?$/gm` 表示在待检测字符串每行的末尾搜索 `at`后跟一个或多个 `.` 的字符串, 并返回全部结果.
<pre>
"/.at(.)?$/" => The fat
cat sat
on the <a href="#learn-regex"><strong>mat.</strong></a>
</pre>
[在线练习](https://regex101.com/r/hoGMkP/1)
<pre>
"/.at(.)?$/gm" => The <a href="#learn-regex"><strong>fat</strong></a>
cat <a href="#learn-regex"><strong>sat</strong></a>
on the <a href="#learn-regex"><strong>mat.</strong></a>
</pre>
[在线练习](https://regex101.com/r/E88WE2/1)
## 额外补充
* *正整数*: `^\d+$`
* *负整数*: `^-\d+$`
* *手机国家号*: `^+?[\d\s]{3,}$`
* *手机号*: `^+?[\d\s]+(?[\d\s]{10,}$`
* *整数*: `^-?\d+$`
* *用户名*: `^[\w\d_.]{4,16}$`
* *数字和英文字母*: `^[a-zA-Z0-9]*$`
* *数字和应为字母和空格*: `^[a-zA-Z0-9 ]*$`
* *密码*: `^(?=^.{6,}$)((?=.*[A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z]))^.*$`
* *邮箱*: `^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})*$`
* *IP4 地址*: `^((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))*$`
* *纯小写字母*: `^([a-z])*$`
* *纯大写字母*: `^([A-Z])*$`
* *URL*: `^(((http|https|ftp):\/\/)?([[a-zA-Z0-9]\-\.])+(\.)([[a-zA-Z0-9]]){2,4}([[a-zA-Z0-9]\/+=%&_\.~?\-]*))*$`
* *VISA 信用卡号*: `^(4[0-9]{12}(?:[0-9]{3})?)*$`
* *日期 (MM/DD/YYYY)*: `^(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2}$`
* *日期 (YYYY/MM/DD)*: `^(19|20)?[0-9]{2}[- /.](0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])$`
* *MasterCard 信用卡号*: `^(5[1-5][0-9]{14})*$`
## 贡献
* 报告问题
* 开放合并请求
* 传播此文档
* 直接和我联系 ziishaned@gmail.com 或 [![Twitter URL](https://img.shields.io/twitter/url/https/twitter.com/ziishaned.svg?style=social&label=Follow%20%40ziishaned)](https://twitter.com/ziishaned)
## 许可证
MIT © [Zeeshan Ahmed](mailto:ziishaned@gmail.com)

538
README-ja.md Normal file
View File

@ -0,0 +1,538 @@
<br/>
<p align="center">
<img src="https://i.imgur.com/bYwl7Vf.png" alt="Learn Regex">
</p><br/>
## 翻訳
* [English](README.md)
* [中文版](README-cn.md)
* [日本語](README-ja.md)
## 正規表現とは
> 正規表現とは文中からある文字列のパターンを見つけるために使用される文字列や記号の組み合わせのことです。
正規表現とは対象の文字列に左から右にマッチするパターンのことを言います。
"Regular expression" (正規表現)という言葉は "regex" や "regexp" などと一言で言い表すことがあります。
正規表現を使うことで文字列の置換・検証・抽出などを行うことが可能です。
アプリケーション中において、ユーザがユーザ名を決めるときに
守るべきルールを定義したいとしましょう。
ユーザ名には文字・数字・アンダースコア・ハイフンが使用可能であるとします。
また、ユーザ名が単調にならないように文字数にも制約を設けるものとします。
この場合、次のような正規表現でユーザ名を検証することができます。
<br/><br/>
<p align="center">
<img src="https://i.imgur.com/ekFpQUg.png" alt="Regular expression">
</p>
この正規表現によって `john_doe, jo-hn_doe, john12_as` などは許容されることになります。
一方で `Jo` は大文字を含む上に短すぎるため許容されません。
## 目次
- [基本的な Matcher](#1-基本的な-matcher)
- [メタ文字](#2-メタ文字)
- [ピリオド](#21-ピリオド)
- [文字集合](#22-文字集合)
- [否定文字集合](#221-否定文字集合)
- [繰り返し](#23-繰り返し)
- [アスタリスク](#231-アスタリスク)
- [プラス記号](#232-プラス記号)
- [疑問符](#233-疑問符)
- [括弧](#24-括弧)
- [文字グループ](#25-文字グループ)
- [選言](#26-選言)
- [特殊文字をエスケープする](#27-特殊文字をエスケープする)
- [アンカー](#28-アンカー)
- [キャレット](#281-キャレット)
- [ドル記号](#282-ドル記号)
- [文字集合の短縮表記](#3-文字集合の短縮表記)
- [前後参照](#4-前後参照)
- [肯定的な先読み](#41-肯定的な先読み)
- [否定的な先読み](#42-否定的な先読み)
- [肯定的な後読み](#43-肯定的な後読み)
- [否定的な後読み](#44-否定的な後読み)
- [フラグ](#5-フラグ)
- [大文字・小文字を区別しない](#51-大文字・小文字を区別しない)
- [グローバル検索](#52-グローバル検索)
- [複数行](#53-複数行)
- [おまけ](#おまけ)
## 1. 基本的な Matcher
文中から特定の文字列を検索する時の正規表現は単なる文字の並びとして表されます。
例えば `the` という正規表現は `t` という文字のあとに `h` が続き、さらに `e` が続くものだと
解釈されます。
<pre>
"the" => The fat cat sat on <a href="#learn-regex"><strong>the</strong></a> mat.
</pre>
[正規表現の動作確認をする](https://regex101.com/r/dmRygT/1)
`123` という正規表現は `123` という文字列にマッチします。
正規表現は正規表現の文字列と入力文字列を1文字ずつ比較しながらマッチングを行います。
また大文字と小文字は区別されるため、 `The``the` にはマッチしません。
<pre>
"The" => <a href="#learn-regex"><strong>The</strong></a> fat cat sat on the mat.
</pre>
[正規表現の動作確認をする](https://regex101.com/r/1paXsy/1)
## 2. メタ文字
メタ文字は正規表現の構成要素として使用される文字のことです。
メタ文字はそれ自身が示す文字を表すものではなく、特別な解釈がなされます。
一部のメタ文字は角括弧内に記述されることで特別な意味を持つものもあります。
メタ文字には次のようなものがあります。
|メタ文字|説明 |
|:------:|---------------------------------------------------------------------------------------------|
|. |ピリオド。改行を除く任意の1文字にマッチ。 |
|[ ] |文字集合。角括弧内の任意の文字にマッチ。 |
|[^ ] |否定文字集合。角括弧内に含まれない任意の文字にマッチ。 |
|* |直前の文字の 0 個以上の並びにマッチ。 |
|+ |直前の文字の 1 個以上の並びにマッチ。 |
|? |直前の文字がオプションであるとみなす。 |
|{n,m} |括弧でくくる。直前の文字が n 個以上 m 個以下続く場合にマッチ。 |
|(xyz) |文字グループ。 xyz という文字列がその順に現れる場合にマッチ。 |
|&#124; |選言。記号の前後の文字列どちらかにマッチ。 |
|&#92; |次に来る文字をエスケープする。予約語 <code>[ ] ( ) { } . * + ? ^ $ \ &#124;</code> にマッチ。|
|^ |入力値の開始にマッチする。 |
|$ |入力値の終了にマッチする。 |
## 2.1 ピリオド
ピリオド `.` は最もシンプルなメタ文字の例です。
メタ文字 `.` は任意の 1 文字にマッチします。
キャリッジリターンと改行にはマッチしません。
例えば `.ar` は任意の文字の後に `a``r` が続く文字列にマッチします。
<pre>
".ar" => The <a href="#learn-regex"><strong>car</strong></a> <a href="#learn-regex"><strong>par</strong></a>ked in the <a href="#learn-regex"><strong>gar</strong></a>age.
</pre>
[正規表現の動作確認をする](https://regex101.com/r/xc9GkU/1)
## 2.2 文字集合
文字集合は文字クラスとも呼ばれます。
文字集合を指定するには角括弧でくくります。
文字の範囲を指定するにはハイフンを使用します。
角括弧内の文字の記述順はマッチングには関係ありません。
例えば `[Tt]he` という正規表現は大文字 `T` または小文字 `t` の後に `h`, `e` が続く文字列を表します。
<pre>
"[Tt]he" => <a href="#learn-regex"><strong>The</strong></a> car parked in <a href="#learn-regex"><strong>the</strong></a> garage.
</pre>
[正規表現の動作確認をする](https://regex101.com/r/2ITLQ4/1)
文字集合内でのピリオドは文字としてのピリオドを表します。
`ar[.]` という正規表現は `a` という文字のあとに `r` が続き、さらに `.` という文字が続く文字列を表します。
<pre>
"ar[.]" => A garage is a good place to park a c<a href="#learn-regex"><strong>ar.</strong></a>
</pre>
[正規表現の動作確認をする](https://regex101.com/r/wL3xtE/1)
### 2.2.1 否定文字集合
通常キャレットは文字列の開始を意味するメタ文字ですが、角括弧内で最初に使用されると
文字集合を否定する意味を持つようになります。
例えば `[^c]ar` という正規表現は `c` 以外の任意の文字列の後に
`a`, `r` が続く文字列を表します。
<pre>
"[^c]ar" => The car <a href="#learn-regex"><strong>par</strong></a>ked in the <a href="#learn-regex"><strong>gar</strong></a>age.
</pre>
[正規表現の動作確認をする](https://regex101.com/r/nNNlq3/1)
## 2.3 繰り返し
`+`, `*`, `?` はパターンが何回続くのかを指定するためのメタ文字になります。
これらのメタ文字は異なるシチュエーションで異なる振る舞いをします。
### 2.3.1 アスタリスク
シンボル `*` は直前の文字が 0 個以上続くパターンにマッチします。
`a*` という正規表現は小文字の `a` が 0 個以上続くことを意味します。
しかし文字集合またはクラスの後に現れた場合はその文字集合すべてが続くことを意味します。
例えば `[a-z]*` という正規表現は行内の任意の小文字の列を表します。
<pre>
"[a-z]*" => T<a href="#learn-regex"><strong>he</strong></a> <a href="#learn-regex"><strong>car</strong></a> <a href="#learn-regex"><strong>parked</strong></a> <a href="#learn-regex"><strong>in</strong></a> <a href="#learn-regex"><strong>the</strong></a> <a href="#learn-regex"><strong>garage</strong></a> #21.
</pre>
[正規表現の動作確認をする](https://regex101.com/r/7m8me5/1)
シンボル `*` はメタ文字 `.` と合わせて `.*` のように使用することで
任意の文字列を表現できます。
またスペースを表す `\s` と併用することで空白文字を表現できます。
例えば `\s*cat\s*` という正規表現は 0 個以上のスペースの後に
小文字の `c`, `a`, `t` が続き、その後に 0 個以上のスペースが続きます。
<pre>
"\s*cat\s*" => The fat<a href="#learn-regex"><strong> cat </strong></a>sat on the <a href="#learn-regex">con<strong>cat</strong>enation</a>.
</pre>
[正規表現の動作確認をする](https://regex101.com/r/gGrwuz/1)
### 2.3.2 プラス記号
シンボル `+` は直前の文字が 1 個以上続くパターンにマッチします。
例えば `c.+t` という正規表現は小文字の `c` の後に
任意の 1 文字が続き、さらに `t` が続くことを意味します。
<pre>
"c.+t" => The fat <a href="#learn-regex"><strong>cat sat on the mat</strong></a>.
</pre>
[正規表現の動作確認をする](https://regex101.com/r/Dzf9Aa/1)
### 2.3.3 疑問符
正規表現におけるメタ文字 `?` は直前の文字がオプションであることを意味します。
すなわち直前の文字が 0 個または 1 個現れることを意味します。
例えば `[T]?he` という正規表現は大文字の `T` が 0 個または 1 個出現し、
その後に小文字の `h`, `e` が続くことを意味します。
<pre>
"[T]he" => <a href="#learn-regex"><strong>The</strong></a> car is parked in the garage.
</pre>
[正規表現の動作確認をする](https://regex101.com/r/cIg9zm/1)
<pre>
"[T]?he" => <a href="#learn-regex"><strong>The</strong></a> car is parked in t<a href="#learn-regex"><strong>he</strong></a> garage.
</pre>
[正規表現の動作確認をする](https://regex101.com/r/kPpO2x/1)
## 2.4 括弧
正規表現における括弧は数量子とも呼ばれますが、文字列がいくつ現れるかを示すために使用されます。
例えば、`[0-9]{2,3}` という正規表現は 2 桁以上 3 桁以下の数字
0 から 9 の数字で表された文字列)にマッチします。
<pre>
"[0-9]{2,3}" => The number was 9.<a href="#learn-regex"><strong>999</strong></a>7 but we rounded it off to <a href="#learn-regex"><strong>10</strong></a>.0.
</pre>
[正規表現の動作確認をする](https://regex101.com/r/juM86s/1)
2つ目の数値は省略できます。
例えば `[0-9]{2,}` という正規表現は 2 桁以上の数字を意味します。
カンマも省略することができ、その場合 `[0-9]{3}` という正規表現はちょうど 3 桁の数字を意味します。
<pre>
"[0-9]{2,}" => The number was 9.<a href="#learn-regex"><strong>9997</strong></a> but we rounded it off to <a href="#learn-regex"><strong>10</strong></a>.0.
</pre>
[正規表現の動作確認をする](https://regex101.com/r/Gdy4w5/1)
<pre>
"[0-9]{3}" => The number was 9.<a href="#learn-regex"><strong>999</strong></a>7 but we rounded it off to 10.0.
</pre>
[正規表現の動作確認をする](https://regex101.com/r/Sivu30/1)
## 2.5 文字グループ
文字グループは括弧 `(...)` 内にパターンを記述してグループ分けをするために使用します。
前述の通り、正規表現においては数量子を文字の後に置いた場合は
その直前の文字の繰り返しを意味します。しかし、文字グループの後に数量子を置いた場合は
文字グループ全体が繰り返すことを意味します。
例えば、 `(ab)*` という正規表現は "ab" という文字列の 0 個以上の繰り返しにマッチします。
文字グループ内では選言 `|` も使用することができます。
例えば、`(c|g|p)ar` という正規表現は小文字の `c`, `g`, `p` のいずれかの後に
`a` が続き、さらに `r` が続くことを意味します。
<pre>
"(c|g|p)ar" => The <a href="#learn-regex"><strong>car</strong></a> is <a href="#learn-regex"><strong>par</strong></a>ked in the <a href="#learn-regex"><strong>gar</strong></a>age.
</pre>
[正規表現の動作確認をする](https://regex101.com/r/tUxrBG/1)
## 2.6 選言
正規表現における縦棒 `|` は選言として使用されます。
選言は複数の正規表現からなる条件式のようなものです。
もしかすると文字集合と選言が同じものと感じるかもしれません。
この 2 つの大きな違いは文字集合は文字単位で評価されるのに対して選言は正規表現単位で評価されます。
例えば `(T|t)he|car` という正規表現は大文字の `T` または小文字の `t` の後に
小文字の `h`, `e` が続くか、または小文字の `c` の後に `a`, `r` が続くことを意味します。
<pre>
"(T|t)he|car" => <a href="#learn-regex"><strong>The</strong></a> <a href="#learn-regex"><strong>car</strong></a> is parked in <a href="#learn-regex"><strong>the</strong></a> garage.
</pre>
[正規表現の動作確認をする](https://regex101.com/r/fBXyX0/1)
## 2.7 特殊文字をエスケープする
バックスラッシュ `\` は正規表現内で次に来る文字をエスケープするために使用されます。
これを使うと予約語 `{ } [ ] / \ + * . $ ^ | ?`
記号として指定できるようになります。
例えば `.` という正規表現は改行を除く任意の文字として使用されますが、
`(f|c|m)at\.?` という正規表現では `.` 自体にマッチします。
この正規表現は小文字の `f`, `c` または `m` の後に小文字の `a`, `t` が続き、
さらに `.` が 0 個または 1 個続きます。
<pre>
"(f|c|m)at\.?" => The <a href="#learn-regex"><strong>fat</strong></a> <a href="#learn-regex"><strong>cat</strong></a> sat on the <a href="#learn-regex"><strong>mat.</strong></a>
</pre>
[正規表現の動作確認をする](https://regex101.com/r/DOc5Nu/1)
## 2.8 アンカー
正規表現内でマッチング文字列の開始または終了であることをチェックするために
アンカーを使うことができます。
アンカーには 2 種類あり、1 つ目が開始を表すキャレット `^`
2 つ目が終了を表すドル記号 `$` です。
### 2.8.1 キャレット
キャレット `^` は文字列の開始かどうかを調べるために使用します。
次の正規表現 `^a` は入力文字列 `abc` に対してa が開始文字列なら)`a` にマッチします。
しかし `^b` という正規表現は前の文字列に対してはどれにもマッチしません。
"b" は `abc` という入力文字列の開始ではないからです。
他の例を見てみます。`^(T|t)he` は大文字の `T` または小文字の `t` から始まる文字列で
その後に小文字の `h`, `e` が続くことを意味します。
<pre>
"(T|t)he" => <a href="#learn-regex"><strong>The</strong></a> car is parked in <a href="#learn-regex"><strong>the</strong></a> garage.
</pre>
[正規表現の動作確認をする](https://regex101.com/r/5ljjgB/1)
<pre>
"^(T|t)he" => <a href="#learn-regex"><strong>The</strong></a> car is parked in the garage.
</pre>
[正規表現の動作確認をする](https://regex101.com/r/jXrKne/1)
### 2.8.2 ドル記号
ドル記号 `$` は文字列の終了かどうかを調べるために使用します。
例えば `(at\.)$` という正規表現は小文字の `a` の後に
小文字の `t` が続き、最後は `.` で終わることを意味しています。
<pre>
"(at\.)" => The fat c<a href="#learn-regex"><strong>at.</strong></a> s<a href="#learn-regex"><strong>at.</strong></a> on the m<a href="#learn-regex"><strong>at.</strong></a>
</pre>
[正規表現の動作確認をする](https://regex101.com/r/y4Au4D/1)
<pre>
"(at\.)$" => The fat cat. sat. on the m<a href="#learn-regex"><strong>at.</strong></a>
</pre>
[正規表現の動作確認をする](https://regex101.com/r/t0AkOd/1)
## 3. 文字集合の短縮表記
正規表現ではよく使われる文字集合に対して短縮表記が提供されており、
便利なショートカットとして使用できます。
省略表記には次のようなものがあります。
|短縮表記|説明 |
|:------:|-----------------------------------|
|. |改行を除く任意の文字 |
|\w |英数字にマッチ: `[a-zA-Z0-9_]` |
|\W |英数字以外にマッチ: `[^\w]` |
|\d |数字にマッチ: `[0-9]` |
|\D |数字以外にマッチ: `[^\d]` |
|\s |スペースにマッチ: `[\t\n\f\r\p{Z}]`|
|\S |スペース以外にマッチ: `[^\s]` |
## 4. 前後参照
しばしば前後参照とも呼ばれる先読みと後読みは **非キャプチャグループ**
(パターンのマッチングはするがマッチングリストには含まれない)という
特殊な扱いがなされる機能です。
前後参照はあるパターンが別のあるパターンよりも先行または後続して現れることを示すために使用されます。
例えば入力文字列 `$4.44 and $10.88` に対して `$` に続く全ての数字を取得することを考えます。
そのためには `(?<=\$)[0-9\.]*` という正規表現を使用します。
これは `$` に続き `.` を含む全ての数字を指すことになります。
次のような前後参照が正規表現で使用されます。
|記号 |説明 |
|:----:|--------------|
|?= |肯定的な先読み|
|?! |否定的な先読み|
|?<= |肯定的な後読み|
|?<! |否定的な後読み|
### 4.1 肯定的な先読み
肯定的な先読みはあるパターンが注目しているパターンよりも後続していることを示すための機能です。
マッチングの結果には注目しているパターンだけが含まれます。
肯定的な先読みを定義するには括弧を使用します。
その括弧の中で疑問符と等号を合わせて `(?=...)` のようにします。
先読みのパターンは括弧の中の等号の後に記述します。
例えば `[T|t]he(?=\sfat)` という正規表現は小文字の `t` か大文字の `T` のどちらかの後に `h`, `e` が続きます。
括弧内で肯定的な先読みを定義していますが、これは `The` または `the` の後に
`fat` が続くことを表しています。
<pre>
"[T|t]he(?=\sfat)" => <a href="#learn-regex"><strong>The</strong></a> fat cat sat on the mat.
</pre>
[正規表現の動作確認をする](https://regex101.com/r/IDDARt/1)
### 4.2 否定的な先読み
否定的な先読みはあるパターンが後続しない全てのマッチング文字列を取得するために使用します。
否定的な先読みは肯定的な先読みと同じように定義しますが、 `=` の代わりに
`!` を使うところが唯一の違いで、`(?!...)` と記述します。
次の正規表現 `[T|t]he(?!\sfat)` について考えてみます。
これはスペースを挟んで `fat` が後続することがない全ての `The` または `the` を得ることができます。
<pre>
"[T|t]he(?!\sfat)" => The fat cat sat on <a href="#learn-regex"><strong>the</strong></a> mat.
</pre>
[正規表現の動作確認をする](https://regex101.com/r/V32Npg/1)
### 4.3 肯定的な後読み
肯定的な後読みは特定のパターンが先行するような文字列を得るために使用します。
定義の仕方は `(?<=...)` とします。
例えば `(?<=[T|t]he\s)(fat|mat)` という正規表現は
`The` または `the` の後に続く全ての `fat` または `mat` が取得できます。
<pre>
"(?<=[T|t]he\s)(fat|mat)" => The <a href="#learn-regex"><strong>fat</strong></a> cat sat on the <a href="#learn-regex"><strong>mat</strong></a>.
</pre>
[正規表現の動作確認をする](https://regex101.com/r/avH165/1)
### 4.4 否定的な後読み
否定的な後読みは特定のパターンが先行しない全ての文字列を得るために使用します。
定義の仕方は `(?<!...>)` とします。
例えば `(?<!(T|t)he\s)(cat)``The` または `the` に続いていない全ての `cat` が取得できます。
<pre>
"(?&lt;![T|t]he\s)(cat)" => The cat sat on <a href="#learn-regex"><strong>cat</strong></a>.
</pre>
[正規表現の動作確認をする](https://regex101.com/r/8Efx5G/1)
## 5. フラグ
フラグは修飾子とも呼ばれ、正規表現の結果を修正するために使用されます。
フラグは任意の順序・組み合わせで使用でき、正規表現では必要不可欠な機能です。
|フラグ|説明 |
|:----:|------------------------------------------------------------------------|
|i |大文字・小文字を区別しない: マッチングで大文字・小文字が区別されなくなる|
|g |グローバル検索: 入力文字列の全マッチ列を検索する |
|m |複数行: 複数行をマッチさせるためのアンカー |
### 5.1 大文字・小文字を区別しない
修飾子 `i` は大文字・小文字を区別しなくないときに使用します。
例えば `/The/gi` という正規表現は大文字の `T` の後に小文字の `h`, `e` が続くという意味ですが、
最後の `i` で大文字・小文字を区別しない設定にしています。
文字列内の全マッチ列を検索したいのでフラグ `g` も渡しています。
<pre>
"The" => <a href="#learn-regex"><strong>The</strong></a> fat cat sat on the mat.
</pre>
[正規表現の動作確認をする](https://regex101.com/r/dpQyf9/1)
<pre>
"/The/gi" => <a href="#learn-regex"><strong>The</strong></a> fat cat sat on <a href="#learn-regex"><strong>the</strong></a> mat.
</pre>
[正規表現の動作確認をする](https://regex101.com/r/ahfiuh/1)
### 5.2 グローバル検索
修飾子 `g` はグローバル検索(最初のマッチ列を検索する代わりに全マッチ列を検索する)を
行うために使用します。
例えば `/.(at)/g` という正規表現は、改行を除く任意の文字列の後に
小文字の `a`, `t` が続きます。正規表現の最後にフラグ `g` を渡すことで
入力文字列内の全マッチ列を検索するようにしています。
<pre>
"/.(at)/" => The <a href="#learn-regex"><strong>fat</strong></a> cat sat on the mat.
</pre>
[正規表現の動作確認をする](https://regex101.com/r/jnk6gM/1)
<pre>
"/.(at)/g" => The <a href="#learn-regex"><strong>fat</strong></a> <a href="#learn-regex"><strong>cat</strong></a> <a href="#learn-regex"><strong>sat</strong></a> on the <a href="#learn-regex"><strong>mat</strong></a>.
</pre>
[正規表現の動作確認をする](https://regex101.com/r/dO1nef/1)
### 5.3 複数行
修飾子 `m` は複数行でマッチさせたいときに使用します。
前述で `(^, $)` という入力文字列の開始と終了を示すためのアンカーについて説明しましたが、
フラグ `m` は複数行でマッチさせるためのアンカーとして使用できます。
例えば `/at(.)?$/gm` という正規表現は小文字の `a`, `t` に続き、改行を除く
任意の文字が 0 個または 1 個続くという意味ですが、
フラグ `m` を渡すことで入力文字列の各行でパターンを検索させることができます。
<pre>
"/.at(.)?$/" => The fat
cat sat
on the <a href="#learn-regex"><strong>mat.</strong></a>
</pre>
[正規表現の動作確認をする](https://regex101.com/r/hoGMkP/1)
<pre>
"/.at(.)?$/gm" => The <a href="#learn-regex"><strong>fat</strong></a>
cat <a href="#learn-regex"><strong>sat</strong></a>
on the <a href="#learn-regex"><strong>mat.</strong></a>
</pre>
[正規表現の動作確認をする](https://regex101.com/r/E88WE2/1)
## おまけ
* *正の整数*: `^\d+$`
* *負の整数*: `^-\d+$`
* *米国の電話番号*: `^+?[\d\s]{3,}$`
* *コード付きの米国の電話番号*: `^+?[\d\s]+(?[\d\s]{10,}$`
* *整数*: `^-?\d+$`
* *ユーザ名*: `^[\w.]{4,16}$`
* *英数字*: `^[a-zA-Z0-9]*$`
* *スペース込みの英数字*: `^[a-zA-Z0-9 ]*$`
* *パスワード*: `^(?=^.{6,}$)((?=.*[A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z]))^.*$`
* *Eメール*: `^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})*$`
* *IPv4 アドレス*: `^((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))*$`
* *小文字のみ*: `^([a-z])*$`
* *大文字のみ*: `^([A-Z])*$`
* *URL*: `^(((http|https|ftp):\/\/)?([[a-zA-Z0-9]\-\.])+(\.)([[a-zA-Z0-9]]){2,4}([[a-zA-Z0-9]\/+=%&_\.~?\-]*))*$`
* *VISA クレジットカード番号*: `^(4[0-9]{12}(?:[0-9]{3})?)*$`
* *日付 (DD/MM/YYYY)*: `^(0?[1-9]|[12][0-9]|3[01])[- /.](0?[1-9]|1[012])[- /.](19|20)?[0-9]{2}$`
* *日付 (MM/DD/YYYY)*: `^(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2}$`
* *日付 (YYYY/MM/DD)*: `^(19|20)?[0-9]{2}[- /.](0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])$`
* *MasterCard クレジットカード番号*: `^(5[1-5][0-9]{14})*$`
* *ハッシュタグ*: 前の文字列を含む (abc123#xyz456) または角括弧内にスペースを含む (#[foo bar]) : `\S*#(?:\[[^\]]+\]|\S+)`
* *@mentions*: `\B@[a-z0-9_-]+`
## 貢献する
* 課題を発行する
* 修正をプルリクエストする
* ドキュメントを普及させる
* 作者に直接連絡を取る: ziishaned@gmail.com または [![Twitter URL](https://img.shields.io/twitter/url/https/twitter.com/ziishaned.svg?style=social&label=Follow%20%40ziishaned)](https://twitter.com/ziishaned)
## ライセンス
MIT © [Zeeshan Ahmed](mailto:ziishaned@gmail.com)

View File

@ -3,8 +3,16 @@
<img src="https://i.imgur.com/bYwl7Vf.png" alt="Learn Regex">
</p><br/>
<<<<<<< HEAD
[中文版](README-zh-simple.md)
=======
## Translations:
* [English](README.md)
* [中文版](README-cn.md)
* [日本語](README-ja.md)
>>>>>>> zeeshanu/master
## What is Regular Expression?
@ -14,9 +22,9 @@ A regular expression is a pattern that is matched against a subject string from
mouthful, you will usually find the term abbreviated as "regex" or "regexp". Regular expression is used for replacing a text within
a string, validating form, extract a substring from a string based upon a pattern match, and so much more.
Imagine you are writing an application and you want to set the rules when user choosing their username. We want the username can
contains letter, number, underscore and hyphen. We also want to limit the number of characters in username so it does not look ugly.
We use the following regular expression to validate a username:
Imagine you are writing an application and you want to set the rules for when a user chooses their username. We want to
allow the username to contain letters, numbers, underscores and hyphens. We also want to limit the number of
characters in username so it does not look ugly. We use the following regular expression to validate a username:
<br/><br/>
<p align="center">
<img src="https://i.imgur.com/ekFpQUg.png" alt="Regular expression">
@ -57,7 +65,7 @@ contains uppercase letter and also it is too short.
## 1. Basic Matchers
A regular expression is just a pattern of letters and digits that we use to perform search in a text. For example, the regular expression
A regular expression is just a pattern of characters that we use to perform search in a text. For example, the regular expression
`the` means: the letter `t`, followed by the letter `h`, followed by the letter `e`.
<pre>
@ -79,7 +87,7 @@ case-sensitive so the regular expression `The` would not match the string `the`.
## 2. Meta Characters
Meta characters are the building blocks of the regular expressions. Meta characters do not stand for themselves but instead are
interpreted in some special way. Some meta characters have a special meaning that are written inside the square brackets.
interpreted in some special way. Some meta characters have a special meaning and are written inside square brackets.
The meta characters are as follows:
|Meta character|Description|
@ -100,7 +108,7 @@ The meta characters are as follows:
## 2.1 Full stop
Full stop `.` is the simplest example of meta character. The meta character `.` matches any single character. It will not match return
or new line characters. For example, the regular expression `.ar` means: any character, followed by the letter `a`, followed by the
or newline characters. For example, the regular expression `.ar` means: any character, followed by the letter `a`, followed by the
letter `r`.
<pre>
@ -171,8 +179,8 @@ zero or more spaces.
### 2.3.2 The Plus
The symbol `+` matches one or more repetitions of the preceding character. For example, the regular expression `c.+t` means: lowercase
letter `c`, followed by any number of character, followed by the lowercase character `t`.
The symbol `+` matches one or more repetitions of the preceding character. For example, the regular expression `c.+t` means: lowercase
letter `c`, followed by at least one character, followed by the lowercase character `t`.
<pre>
"c.+t" => The fat <a href="#learn-regex"><strong>cat sat on the mat</strong></a>.
@ -228,7 +236,7 @@ the comma the regular expression `[0-9]{3}` means: Match exactly 3 digits.
## 2.5 Character Group
Character group is a group of sub-patterns that is written inside Parentheses `(...)`. As we discussed before that in regular expression
if we put a quantifier after a character than it will repeat the preceding character. But if we put quantifier after a character group then
if we put a quantifier after a character then it will repeat the preceding character. But if we put quantifier after a character group then
it repeats the whole character group. For example, the regular expression `(ab)*` matches zero or more repetitions of the character "ab".
We can also use the alternation `|` meta character inside character group. For example, the regular expression `(c|g|p)ar` means: lowercase character `c`,
`g` or `p`, followed by character `a`, followed by character `r`.
@ -257,7 +265,7 @@ or lowercase character `c`, followed by lowercase character `a`, followed by low
Backslash `\` is used in regular expression to escape the next character. This allows to to specify a symbol as a matching character
including reserved characters `{ } [ ] / \ + * . $ ^ | ?`. To use a special character as a matching character prepend `\` before it.
For example, the regular expression `.` is used to match any character except new line. Now to match `.` in an input string the regular
For example, the regular expression `.` is used to match any character except newline. Now to match `.` in an input string the regular
expression `(f|c|m)at\.?` means: lowercase letter `f`, `c` or `m`, followed by lowercase character `a`, followed by lowercase letter
`t`, followed by optional `.` character.
@ -269,9 +277,10 @@ expression `(f|c|m)at\.?` means: lowercase letter `f`, `c` or `m`, followed by l
## 2.8 Anchors
In regular expressions, to check if the matching symbol is the starting symbol or ending symbol of the input string for this purpose
we use anchors. Anchors are of two types: First type is Caret `^` that check if the matching character is the start character of the
input and the second type is Dollar `$` that checks if matching character is the last character of the input string.
In regular expressions, we use anchors to check if the matching symbol is the starting symbol or ending symbol of the
input string. Anchors are of two types: First type is Caret `^` that check if the matching character is the start
character of the input and the second type is Dollar `$` that checks if matching character is the last character of the
input string.
### 2.8.1 Caret
@ -331,7 +340,7 @@ regular expressions. The shorthand character sets are as follows:
Lookbehind and lookahead sometimes known as lookaround are specific type of ***non-capturing group*** (Use to match the pattern but not
included in matching list). Lookaheads are used when we have the condition that this pattern is preceded or followed by another certain
pattern. For example, we want to get all numbers that are preceded by `$` character from the following input string `$4.44 and $10.88`.
We will use following regular expression `(?<=\$)[0-9\.]*` which means: get all the numbers which contains `.` character and preceded
We will use following regular expression `(?<=\$)[0-9\.]*` which means: get all the numbers which contain `.` character and are preceded
by `$` character. Following are the lookarounds that are used in regular expressions:
|Symbol|Description|
@ -384,7 +393,7 @@ are after the word `The` or `the`.
### 4.4 Negative Lookbehind
Negative lookbehind is used to get all the matches that are not preceded by a specific pattern. Negative lookbehind is denoted by
`(?<!...)`. For example, the regular expression `(?&lt;!(T|t)he\s)(cat)` means: get all `cat` words from input string that
`(?<!...)`. For example, the regular expression `(?<!(T|t)he\s)(cat)` means: get all `cat` words from input string that
are not after the word `The` or `the`.
<pre>
@ -472,20 +481,22 @@ line. And because of `m` flag now regular expression engine matches pattern at t
* *US Phone Number*: `^+?[\d\s]{3,}$`
* *US Phone with code*: `^+?[\d\s]+(?[\d\s]{10,}$`
* *Integers*: `^-?\d+$`
* *Username*: `^[\w\d_.]{4,16}$`
* *Username*: `^[\w.]{4,16}$`
* *Alpha-numeric characters*: `^[a-zA-Z0-9]*$`
* *Alpha-numeric characters with spaces*: `^[a-zA-Z0-9 ]*$`
* *Password*: `^(?=^.{6,}$)((?=.*[A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z]))^.*$`
* *email*: `^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})*$`
* *email*: `^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})*$`
* *IPv4 address*: `^((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))*$`
* *Lowercase letters only*: `^([a-z])*$`
* *Uppercase letters only*: `^([A-Z])*$`
* *URL*: `^(((http|https|ftp):\/\/)?([[a-zA-Z0-9]\-\.])+(\.)([[a-zA-Z0-9]]){2,4}([[a-zA-Z0-9]\/+=%&_\.~?\-]*))*$`
* *VISA credit card numbers*: `^(4[0-9]{12}(?:[0-9]{3})?)*$`
* *Date (DD/MM/YYYY)*: `^(0?[1-9]|[12][0-9]|3[01])[- /.](0?[1-9]|1[012])[- /.](19|20)?[0-9]{2}$`
* *Date (MM/DD/YYYY)*: `^(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2}$`
* *Date (YYYY/MM/DD)*: `^(19|20)?[0-9]{2}[- /.](0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])$`
* *MasterCard credit card numbers*: `^(5[1-5][0-9]{14})*$`
* *Hashtags*: Including hashtags with preceding text (abc123#xyz456) or containing white spaces within square brackets (#[foo bar]) : `\S*#(?:\[[^\]]+\]|\S+)`
* *@mentions*: `\B@[a-z0-9_-]+`
## Contribution
* Report issues