# 그루핑

***

ABC 문자열이 계속해서 반복되는지 조사하는 정규식을 작성해야하는경우 필요한 것이 바로 **그루핑(Grouping)** 입니다.

정규식 표현은 다음과 같습니다.

**'(ABC)+'**

## 소괄호 그루핑

그룹을 만들어 주는 메타 문자는 바로 **소괄호 ()** 입니다.

```python
import re

p = re.compile('(ABC)+')
m = p.search('ABCABCABC OK?')

print(m) # <re.Match object; span=(0, 9), match='ABCABCABC'>
print(m.group()) # ABCABCABC
```

다음 예제를 예로 들겠습니다.

```python
p = re.compile(r"\w+\s+\d+[-]\d+[-]\d+")
m = p.search("park 010-1234-1234")
```

위 예제는 이름 + " " + 전화번호 형태의 정규식 패턴입니다. 이중에서 이름만 추출해 내고 싶다면 바로 그루핑을 적용하는것입니다.

## 다중 그루핑

1. 한개 그루핑

```python
p = re.compile(r"(\w+)\s+\d+[-]\d+[-]\d+")

m = p.search("choi 010-1234-1234")
print(m.group(1)) # park
```

1. 두개 그루핑

```python
p = re.compile(r"(\w+)\s+(\d+[-]\d+[-]\d+)")

m = p.search("park 010-1234-1234")
print(m.group(2)) # 010-1234-1234
```

1. 두개이상의 그루핑

```python
p = re.compile(r"(\w+)\s+((\d+)[-]\d+[-]\d+)")

m = p.search("park 010-1234-1234")
print(m.group(3)) # 010
```

이름 부분에 해당하는 부분을 \*\*(\w+)\*\*로 그루핑 한다면 그부분의 문자열만 추출 할 수 있습니다.

| group(인덱스) | 설명                |
| ---------- | ----------------- |
| group(0)   | 매치된 전체 문자열        |
| group(1)   | 첫 번째 그룹에 해당되는 문자열 |
| group(2)   | 두 번째 그룹에 해당되는 문자열 |
| group(n)   | n 번째 그룹에 해당되는 문자열 |

## 그루핑 변수선언 (네이밍)

정규식 안에 그룹이 상당히 많아 질 경우는 그룹이 10개만 되어도 가독성이 현저히 떨어 질 것입니다. 따라서 그룹을 직접 네이밍하여 코드의 가독성을 높이는 것이 좋습니다.

정규 표현식에서의 그루핑의 변수 선언은 다음과 같이 할 수 있습니다.(위의 핸드폰 추출 정규식의 예제 적용)

**(?P\w+)\s+((\d+)\[-]\d+\[-]\d+)**

```python
p = re.compile(r"(?P<name>\w+)\s+((\d+)[-]\d+[-]\d+)")
m = p.search("choi 010-1234-1234")
print(m.group("name")) # choi
```

위 예 에서 볼 수 있듯이 name 이라는 그룹이름으로 참조 할 수 있습니다. 그룹 이름을 사용하면 정규식 안에서 재참조 하는 것도 가능합니다.


---

# 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://sinbum.gitbook.io/blog/undefined-1/python/pythonuseguide/regexpression/grouping.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.
