---
title: Python RegEx
description: "> ## Python RegEx > > > > A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern. > > > > RegEx (Regular Expression) буюу тогтмол илэрхийлэл нь тэмдэгтийн дараалал бөгөөд хайлтын загвар үүсгэдэг. >…"
url: "https://apprentice.mn/docs/python-regex/"
updated: "2024-07-31"
category: Python
---

# Python RegEx

> ## Python RegEx
>
>
>
> A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern.
>
>
>
> RegEx (Regular Expression) буюу тогтмол илэрхийлэл нь тэмдэгтийн дараалал бөгөөд хайлтын загвар үүсгэдэг.
>
>
>
> RegEx can be used to check if a string contains the specified search pattern.
>
>
>
> RegEx нь тэмдэгт мөр тодорхой хайлтын загвар агуулж байгаа эсэхийг шалгах боломжтой.

## RegEx Module – RegEx модуль

Python has a built-in package called `re`, which can be used to work with Regular Expressions.

Python нь Тогтмол Илэрхийлэлтэй ажиллах `re` гэсэн өвөрмөц багцийг агуулдаг.

Import the `re` module:

Модуль импортлох `re`:

`import re`

## RegEx in Python – Python дахь RegEx

When you have imported the `re` module, you can start using regular expressions:

`re` модулийг импортолсны дараа та тогтмол илэрхийллийг ашиглах боломжтой:

#### Example – Жишээ

Search the string to see if it starts with “The” and ends with “Spain”:

Тэмдэгт мөрийн эхлэл нь “The”, төгсгөл нь “Spain” байна уу шалгах:   

`import retxt = "The rain in Spain"x = re.search("^The.*Spain$", txt)`

## RegEx Functions – RegEx функцууд

The `re` module offers a set of functions that allows us to search a string for a match:

`re` модуль нь тохирох мөрийг хайх боломжийг олгодог багц функцуудыг санал болгодог:

| Function Функц | Description Тайлбар |
| --- | --- |
| findall | Returns a list containing all matches Бүх таарах зүйлсийг агуулсан жагсаалтыг буцаана |
| search | Returns a Match object if there is a match anywhere in the string Тэмдэгт мөрний хаа нэгтээ таарах зүйл байвал Match объект буцаана |
| split | Returns a list where the string has been split at each match Тэмдэгт мөрийг тус бүрийн таарсан газарт хувааж, жагсаалт буцаана |
| sub | Replaces one or many matches with a string Нэг эсвэл олон таарах зүйлсийг тэмдэгтээр орлуулна |

---

  

---

## Metacharacters – Мета тэмдэгтүүд

Metacharacters are characters with a special meaning:

Мета тэмдэгтүүд нь тусгай утгатай тэмдэгтүүд юм:

| Character Тэмдэгт | Description Тайлбар | Example Жишээ |   |
| --- | --- | --- | --- |
| [] | A set of characters Тэмдэгтүүдийн багц | “[a-m]” |   |
| \ | Signals a special sequence (can also be used to escape special characters) Тусгай дарааллыг илтгэнэ (мөн тусгай тэмдэгтүүдийг орхиход ашиглаж болно)  | “\d” |   |
| . | Any character (except newline character) Ямар ч тэмдэгт (newline тэмдэгтээс бусад)  | “he..o” |   |
| ^ | Starts with …-аар эхэлдэг  | “^hello” |   |
| $ | Ends with …-аар төгсдөг  | “planet$” |   |
| * | Zero or more occurrences Тэг эсвэл олон тохиолдол  | “he.*o” |   |
| + | One or more occurrences Нэг эсвэл олон тохиолдол  | “he.+o” |   |
| ? | Zero or one occurrences Тэг эсвэл нэг тохиолдол  | “he.?o” |   |
| {} | Exactly the specified number of occurrences Тодорхой тооны тохиолдлууд  | “he.{2}o” |   |
| | | Either or Аль нэг нь | “falls|stays” |   |
| () | Capture and group Барьж авах, бүлэглэх |   |   |

---

## Special Sequences – Тусгай дарааллууд

A special sequence is a `` followed by one of the characters in the list below, and has a special meaning:

Тусгай дараалал гэдэг нь `` тэмдэгтээс эхэлсэн дараалал бөгөөд тусгай утгатай:

| Character Тэмдэгт | Description Тайлбар | Example Жишээ |   |
| --- | --- | --- | --- |
| \A | Returns a match if the specified characters are at the beginning of the string Тэмдэгт мөрний эхэнд байгаа тэмдэгтүүдийг тааруулдаг | “\AThe” |   |
| \b | Returns a match where the specified characters are at the beginning or at the end of a word (the “r” in the beginning is making sure that the string is being treated as a “raw string”) Тэмдэгт мөрний эхэнд эсвэл төгсгөлд байгаа тэмдэгтүүдийг тааруулдаг  | r”\bain” r”ain\b” |   |
| \B | Returns a match where the specified characters are present, but NOT at the beginning (or at the end) of a word (the “r” in the beginning is making sure that the string is being treated as a “raw string”) Үгийн эхэнд (эсвэл төгсгөлд) БИШ, заасан тэмдэгтүүд байгаа тохирохыг буцаана | r”\Bain” r”ain\B” |   |
| \d | Returns a match where the string contains digits (numbers from 0-9) Тэмдэгт мөр нь цифр агуулсан эсэхийг шалгадаг(0-ээс 9 хүртлэх тоонууд) | “\d” |   |
| \D | Returns a match where the string DOES NOT contain digits Мөрт цифр агуулаагүй тохирохыг буцаана | “\D” |   |
| \s | Returns a match where the string contains a white space character Зай тэмдэгт агуулсан эсэхийг шалгадаг  | “\s” |   |
| \S | Returns a match where the string DOES NOT contain a white space character Зай тэмдэгт агуулаагүй эсэхийг шалгадаг  | “\S” |   |
| \w | Returns a match where the string contains any word characters (characters from a to Z, digits from 0-9, and the underscore _ character) Бүх үгний тэмдэгтүүдийг тааруулдаг (a-z хүртэл, 0-ээс 9 хүртэл, бас доогуур зураас тэмдэгт _) | “\w” |   |
| \W | Returns a match where the string DOES NOT contain any word characters Үгийн тэмдэгт ашиглаагүй тэмдэгтүүдийг шалгах | “\W” |   |
| \Z | Returns a match if the specified characters are at the end of the string Тэмдэгийн төгсгөл тодорхойлсон тэмдэгт эсэхийг шалгана  | “Spain\Z” |   |

---

## Sets

A set is a set of characters inside a pair of square brackets `[]` with a special meaning:

Sets нь квадрат хаалтан доторх тэмдэгтүүдийн багц бөгөөд тусгай утгатай байдаг:

| Set Багц | Description Тайлбар |   |
| --- | --- | --- |
| [arn] | Returns a match where one of the specified characters (`a`, `r`, or `n`) is present Тодорхойлогдсон тэмдэгтүүдийн аль нэг нь байгаа эсэхийг шалгадаг |   |
| [a-n] | Returns a match for any lower case character, alphabetically between `a` and `n` Цагаан толгойн `a`-гаас `n` хүртлэх  таарах бүх жижиг үсэг орсныг нь буцаана  |   |
| [^arn] | Returns a match for any character EXCEPT `a`, `r`, and `n` `a`, `r`, `n` -ээс бусад бүх тэмдэгтийн тохирохыг буцаана |   |
| [0123] | Returns a match where any of the specified digits (`0`, `1`, `2`, or `3`) are present Заасан цифрүүдийн аль нэг нь (0, 1, 2, эсвэл 3) байгаа тохирохыг буцаана |   |
| [0-9] | Returns a match for any digit between `0` and `9` 0-ээс 9-ын тооны хоорон дох тохирохыг буцаана |   |
| [0-5][0-9] | Returns a match for any two-digit numbers from `00` and `59` 00 ба 59 хүртэлх хоёр оронтой тоонуудын тохирохыг буцаана |   |
| [a-zA-Z] | Returns a match for any character alphabetically between `a` and `z`, lower case OR upper case a болон z, жижиг ЭСВЭЛ том үсгийн хооронд цагаан толгойн дарааллаар дурын тэмдэгтийн тохирохыг буцаана |   |
| [+] | In sets, `+`, `*`, `.`, `|`, `()`, `$`,`{}` has no special meaning, so `[+]` means: return a match for any `+` character in the string Багцад,`+`, `*`, `.`, `|`, `()`, `$`,`{}` нь ямар ч онцгой утга агуулдаггүй тул {`+`} нь ямар ч онцгой утгатай биш юм. |   |

---

  

## The findall() Function – findall() функц

The `findall()` function returns a list containing all matches.

`findall()` функц нь бүх таарах зүйлсийг агуулсан жагсаалтыг буцаана.

#### Example – Жишээ

Print a list of all matches:

Бүх тохирох зүйлсийг жагсааж хэвлэх:

`import retxt = "The rain in Spain"x = re.findall("ai", txt)print(x)`

The list contains the matches in the order they are found.

Тус жагсаалтанд олдсон дарааллаар нь таарах зүйлсийг агуулдаг.

If no matches are found, an empty list is returned:

Хэрвээ олдохгүй бол, хоосон жагсаалт буцаана: 

#### Example – Жишээ

Return an empty list if no match was found:

Хэрэв тохирох зүйл олдоогүй бол хоосон жагсаалтыг буцаана уу:

`import retxt = "The rain in Spain"x = re.findall("Portugal", txt)print(x)`

## The search() Function – 

The `search()` function searches the string for a match, and returns a Match object if there is a match.

`search()` функц нь тэмдэгт мөрийн таарах зүйлсийг хайж, хэрэв таарах зүйл байвал Мatch объект буцаана.

If there is more than one match, only the first occurrence of the match will be returned:

Хэрэв хэд хэдэн тохирол байгаа бол зөвхөн эхний тохиолдол нь буцаж ирнэ.

#### Example – Жишээ

Search for the first white-space character in the string:

Тэмдэгт мөрний эхний хоосон зай тэмдэгтийн хайх:

`import retxt = "The rain in Spain"x = re.search("s", txt)print("The first white-space character is located in position:", x.start())`

If no matches are found, the value `None` is returned:

Хэрвээ олохгүй бол, `None` утга буцаана:

#### Example – Жишээ

Make a search that returns no match:

Тохирохгүй хайлт хийж буцаах: 

`import retxt = "The rain in Spain"x = re.search("Portugal", txt)print(x)`

## The split() Function – split() Функц

The `split()` function returns a list where the string has been split at each match:

`split()` функц нь мөрийг тохирох хэсэг бүрээр нь хувааж жагсаалтыг буцаадаг:

#### Example – Жишээ

Split at each white-space character:

Хоосон зай бүрээр хуваах: 

`import retxt = "The rain in Spain"x = re.split("s", txt)print(x)`

You can control the number of occurrences by specifying the `maxsplit` parameter:

Та `maxsplit` параметрийг зааж өгснөөр тохиолдлын тоог оруулах боломжтой:

#### Example – Жишээ

Split the string only at the first occurrence:

Мөрөнд зөвхөн эхний тохиолдол таарах үед хуваах:

`import retxt = "The rain in Spain"x = re.split("s", txt, 1)print(x)`

## The sub() Function – sub() Функц

The `sub()` function replaces the matches with the text of your choice:

`sub()` функц нь таарах зүйлсийг таны сонгосон тэмдэгтээр орлуулна.

#### Example – Жишээ

Replace every white-space character with the number 9:

Хоосон зай болгоныг 9 тоогоор солино уу:

`import retxt = "The rain in Spain"x = re.sub("s", "9", txt)print(x)`

You can control the number of replacements by specifying the `count` parameter:

Та `count` параметрийг зааж өгснөөр орлуулах тоог оруулах боломжтой.

#### Example – Жишээ

Replace the first 2 occurrences:

Эхний 2 тохиолдолд орлуул: 

`import retxt = "The rain in Spain"x = re.sub("s", "9", txt, 2)print(x)`

## Match Object – Тохирох объект

A Match Object is an object containing information about the search and the result.

Тохирох объект нь хайлт болон үр дүнгийн тухай мэдээллийг агуулсан объект юм.

**Note:** If there is no match, the value `None` will be returned, instead of the Match Object.

**Тайлбар:** Хэрэв Тохирох объектийн оронд, тохирох зүйл байхгүй бол `None` утгыг буцаана.

#### Example – Жишээ

Do a search that will return a Match Object:

Тохирох объектыг буцаах хайлт хийнэ үү:

`import retxt = "The rain in Spain"x = re.search("ai", txt)print(x) #this will print an object`

The Match object has properties and methods used to retrieve information about the search, and the result:

Тохирох объект нь хайлт болон үр дүнгийн тухай мэдээллийг агуулсан объект юм.

`.span()` returns a tuple containing the start-, and end positions of the match.
`.span()` таарах зүйлсийн эхлэл болон төгсгөлийн байрлалыг агуулсан tuple-г буцаана

`.string` returns the string passed into the function
`.string` Функцэд дамжуулсан тэмдэгт мөрийг буцаана

`.group()` returns the part of the string where there was a match
`.group()` Таарах зүйлс байгаа хэсгийн тэмдэгт мөрийг буцаана

 

#### Example – Жишээ

Print the position (start- and end-position) of the first match occurrence.

Эхний тохиолдлийн байрлалыг (эхлэх ба төгсгөлийн байрлал) хэвлэ.

The regular expression looks for any words that starts with an upper case “S”:

Том “S” үсгээр эхэлсэн үгийг хай: 

`import retxt = "The rain in Spain"x = re.search(r"bSw+", txt)print(x.span())`

#### Example – Жишээ

Print the string passed into the function:

Функц дамжуулсан мөрийг хэвлэ:

`import retxt = "The rain in Spain"x = re.search(r"bSw+", txt)print(x.string)`

#### Example – Жишээ

Print the part of the string where there was a match.

Мөрийн таарсан хэсгийг хэвлэ:

The regular expression looks for any words that starts with an upper case “S”:

Том “S” үсгээр эхэлсэн үгсийг хай:

`import retxt = "The rain in Spain"x = re.search(r"bSw+", txt)print(x.group())`

**Note:** If there is no match, the value `None` will be returned, instead of the Match Object.

**Тайлбар:** Хэрэв таарсан зүйл байхгүй бол, Тохирох объектын оронд нь `None` утгыг буцаана.

            [https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-regex%2F&linkname=Python%C2%A0RegEx](https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-regex%2F&linkname=Python%C2%A0RegEx)[https://www.addtoany.com/add_to/mastodon?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-regex%2F&linkname=Python%C2%A0RegEx](https://www.addtoany.com/add_to/mastodon?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-regex%2F&linkname=Python%C2%A0RegEx)[https://www.addtoany.com/add_to/email?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-regex%2F&linkname=Python%C2%A0RegEx](https://www.addtoany.com/add_to/email?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-regex%2F&linkname=Python%C2%A0RegEx)[https://www.addtoany.com/share](https://www.addtoany.com/share)
