캡쳐링 그룹(Capturing Group)
- 정규식 패턴 문자열을 통해 매칭한 문자열에서 부분 문자열만 추출하여 따로 참조할 수 있다.
(
PATTERN)
( )
를 통해 그룹을 분리하며, 순서대로 $1
, $2
등과 같이 참조하여 활용한다.
- 그룹 단위로 반복 횟수, 존재 여부 등을 묶어 검사할 수 있다.
const text = "text example <http://dev.rito15.com/route/path?query=value> abcde"
const pattern = "https?:\\/\\/(**\\w+**)?\\.?(**\\w+\\.\\w+**)\\/\\S+"
// Groups: ^^^^^ ^^^^^^^^^^
/* [결과]
Match 1 : <http://dev.rito15.com/route/path?query=value>
Group 1 : dev
Group 2 : rito15.com
*/
넌캡쳐링 그룹(Non-capturing Group)
- 그룹 단위로 반복 횟수, 존재 여부 등을 검사하고 싶으나 매칭 결과에서 따로 그룹으로 참조하고 싶지 않을 때 사용한다.
(?:)
형태로 사용한다.
(?:
PATTERN)
const text = "text example <http://dev.rito15.com/route/path?query=value> abcde"
const pattern = "https?:\\/\\/(?:**\\w+**)?\\.?(**\\w+\\.\\w+**)\\/\\S+"
// Non-Capturing Group: ^^^^^^^
/* [결과]
Match 1 : <http://dev.rito15.com/route/path?query=value>
Group 1 : rito15.com
*/
네임드 캡쳐링 그룹(Named Capturing Group)
- 그룹에 임의의 이름을 붙여, 참조 용이성을 높인다.
(?<name>)
형태로 사용한다.
(?<name>
PATTERN)
const text = "text example <http://dev.rito15.com/route/path?query=value> abcde"
const pattern = "https?:\\/\\/(\\w+)?\\.?(?<domain>**\\w+\\.\\w+**)\\/\\S+"
// Named Capturing Group: ^^^^^^^^^^^^^^^^^^^
/* [결과]
Match 1 : <http://dev.rito15.com/route/path?query=value>
Group 1 : dev
Group domain : rito15.com
*/
참고