# 정규표현식

## 정규표현식(Regular Expression)

> 정규표현식은 문자열에서 특정한 문자를 찾아내는 도구로,\
> 이 도구를 이용하면 수십 줄이 필요한 작업을 한 줄로 끝낼 수 있음

## 1. 컴파일(compile)

컴파일은 검출하고자 하는 패턴을 만드는 일

### 1-1. 정규표현식 리터럴

```javascript
let pattern = /a/
//a라는 텍스트를 찾아내는 정규표현식
```

### 1-2. 정규표현식 객체생성자

```javascript
let pattern = new RegExp('a');
//a라는 텍스트를 찾아내는 정규표현식
```

## 2. 정규표현식 메소드 실행(execution)

> 정규표현식을 컴파일해서 객체를 만든 후, \
> 문자열에서 원하는 문자를 찾아내기

### 2-1. RegExp.exec()

실행결과는 해당 값이 있는 **배열**을 리턴

```javascript
let pattern = new RegExp('a');
pattern.exec('abcde');  //["a"]
pattern.exec('bcdefg'); //null

let pattern = /a./;    // .은 하나의 문자
pattern.exec('abcde'); //["ab"]
```

### 2-2. RegExp.test()

인자 안에 패턴에 해당되는 문자열이 있으면 **true**, 없으면 **false**를 리턴

```javascript
let pattern = /a/;
pattern.test('abcdef'); //true
pattern.text('bcde'); //false
```

### 2-3. String.match()

RegExp.exec()와 비슷

```javascript
let pattern = /a/;
let str = 'abcdef';
str.match(pattern); //["a"]
let str = 'bcdef';
str.match(pattern); // null
```

### 2-4. String.replace() - 치환

문자열에서 패턴을 **검색**해서 이를 **변경한 후**에 변경된 값을 **리턴**

```javascript
let str = 'abcdef';
let pattern = /a/;
str.replace(pattern, 'A'); //"Abcdef"​
```

## 3. 옵션

> 정규표현식 패턴을 만들 때 옵션 설정 가능, 옵션에 따라서 검출되는 데이터가 달라짐

### 3-1. 옵션 i

> i를 붙이면 **대소문자를 구분하지 않음**

```javascript
var xi = /a/;
"Abcde".match(xi); //null
var oi = /a/i;
"Abcde".match(oi); //["A"]
```

### 3-2. 옵션 g

> g를 붙이면 **검색된 모든 결과를 리턴**

```javascript
var xg = /a/;
"abcdea".match(xg); //["a"]
var og = /a/g;
"abcdea".match(og); //["a" , "a"]
```

### 3-3. 옵션 i와 g 혼합

```javascript
var ig = /a/ig;
"AabcAa".match(ig); //["A" , "a" , "A" , "a"]
```

## 4. 캡처

> 괄호 안의 패턴은 마치 변수처럼 재사용 할 수 있고, 이 때 기호 $를 사용

```javascript
let pattern = /(\w+)\s(\w+)/; //\s 는 공백
let str = "coding everybody";
let result = str.replace(pattern, "$2, $1");
//pattern에 해당하는 문자 뒤에 있는 값으로 치환
//$1 = 첫번째 패턴, $2 = 두번째 패턴 ,는 공백
console.log(result); //everybody, coding
```


---

# 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://westsilver.gitbook.io/study-script/javascript/jacascript-start/undefined/undefined-4.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.
