# 정규 표현식

## 정규 표현식

**정규표현식(regular expression)은 문자열에서 특정한 문자를 찾아내는 도구다.** 이 도구를 이용하면 수십줄이 필요한 작업을 한줄로 끝낼 수 있다.

### 컴파일

**컴파일은 검출**하고자 하는 **패턴을 만드는 일**이다.

### 정규표현식 리터럴

```javascript
	var pattern = /a/ //a가 찾고자하는 대상이다. 정규표현식을 패턴에 담는다
```

### 정규표현식 객체 생성자

```javascript
var pattern = new RegExp('a'); // 정규표현식을 패턴에 담는다
```

### 정규표현식 메소드 실행

#### RegExp.exec()

```javascript
	console.log(pattern.exec('abcdef')); // ["a"]
	console.log(pattern.exec('bcdefg')); // null -> a가 존재하지 않기때문에  null을 리
```

**우리가 필요한 정보를 추출**&#x20;

#### RegExp.test()

```javascript
console.log(pattern.test('abcdef')); // true
cnosole.log(pattern.test('bcdefg')); // false
```

**우리가 찾는 정보 존재유무를 확인할때 사**

### 문자열 메소드 실행

#### String.match()

```javascript
console.log('abcdef'.match(pattern)); // ["a"]
console.log('bcdefg'.match(pattern)); // null
```

RegExp.exec()와 비슷하다.

### String.replace()

```javascript
console.log('abcdef'.replace(pattern, 'A'));  // Abcdef
```

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

### 옵션

#### i

```javascript
var xi = /a/;
console.log("Abcde".match(xi)); // null
var oi = /a/i;
console.log("Abcde".match(oi)); // ["A"]; 대문자도 추출해
```

**i를 붙이면 대소문자를 구분하지 않다.**

#### g

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

**g를 붙이면 검색된 모든 결과를 리턴한다.**

### 캡쳐

```javascript
var pattern = /(\w+)\s(\w+)/; // \s -> 공백을 의미함 
var str = "coding everybody";
var result = str.replace(pattern, "$2, $1"); //패턴에 있는 인자를 뒤에 두개의 값으로 치환한다.
// $1 -> 첫번째그룹을 의미 $2 -> 두번째그룹 의
//  \s(공백)은 -> ,공백으로 치환
console.log(result); //everybody, coding 
```

괄호안의 패턴은 마치 변수처럼 재사용할 수 있다. 이 때 기호 $를 사용하는데 아래 코드는 coding과 everybody의 순서를 역전시킨다.

**그룹을 지정하고 지정된 그룹을 가져와서 사용하는것**을 캡쳐라고 한다.

### 치환

```javascript
var urlPattern = /\b(?:https?):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*/gim;
var content = '생활코딩 : http://opentutorials.org/course/1 입니다. 네이버 : http://naver.com 입니다. ';
var result = content.replace(urlPattern, function(url){
    return '<a href="'+url+'">'+url+'</a>';
});
// url을 찾을때마다 replace 내부에 있는 함수를 호출 했다면 이것을 첫번째 인자로 받게되어있음 
console.log(result);
// 결과 -> 생활코딩 : <a href="http://opentutorials.org/course/1">http://opentutorials.org/course/1</a> 입니다. 네이버 : <a href="http://naver.com">http://naver.com</a> 입니다.

```

###

### 추가공부 할 때 참조

* [생활코딩 정규표현식 수업](https://opentutorials.org/course/909)
* [정규표현식을 시각화](http://www.regexper.com/)
* [정규표현식 빌더](http://www.regexr.com/)


---

# 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://leeboa.gitbook.io/study/undefined-13/undefined-9.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.
