RegExp

RegExp 생성자는 패턴을 사용해 텍스트를 판별할 때 사용합니다.

정규 표현식에 대한 소개는 JavaScript 안내서의 정규 표현식 장을 참고하세요.

설명

리터럴 표기법과 생성자

RegExp 객체는 리터럴 표기법과 생성자로써 생성할 수 있습니다.

  • 리터럴 표기법의 매개변수는 두 빗금으로 감싸야 하며 따옴표를 사용하지 않습니다.
  • 생성자 함수의 매개변수는 빗금으로 감싸지 않으나 따옴표를 사용합니다.

다음의 세 표현식은 모두 같은 정규 표현식을 생성합니다.

/ab+c/i
new RegExp(/ab+c/, 'i') // 리터럴
new RegExp('ab+c', 'i') // 생성자

리터럴 표기법은 표현식을 평가할 때 정규 표현식을 컴파일합니다. 정규 표현식이 변하지 않으면 리터럴 표기법을 사용하세요. 예를 들어, 반복문 안에서 사용할 정규 표현식을 리터럴 표기법으로 생성하면 정규 표현식을 매번 다시 컴파일하지 않습니다.

정규 표현식 객체의 생성자(new RegExp('ab+c'))를 사용하면 정규 표현식이 런타임에 컴파일됩니다. 패턴이 변할 가능성이 있거나, 사용자 입력과 같이 알 수 없는 외부 소스에서 가져오는 정규 표현식의 경우 생성자 함수를 사용하세요.

생성자의 플래그

ECMAScript 6부터는 new RegExp(/ab+c/, 'i')처럼, 첫 매개변수가 RegExp이면서 flags를 지정해도 TypeError ("can't supply flags when constructing one RegExp from another")가 발생하지 않고, 매개변수로부터 새로운 정규 표현식을 생성합니다.

생성자 함수를 사용할 경우 보통의 문자열 이스케이프 규칙(특수 문자를 문자열에 사용할 때 앞에 역빗금(\)을 붙이는 것)을 준수해야 합니다.

예를 들어 다음 두 줄은 동일한 정규 표현식을 생성합니다.

let re = /\w+/
let re = new RegExp('\\w+')

Perl  형태의 RegExp 속성

일부 RegExp 속성은 같은 값에 대해 긴 이름과 짧은 (Perl 형태의) 이름 모두 가지고 있습니다. (Perl은 JavaScript가 정규 표현식을 만들 때 참고한 프로그래밍 언어입니다.)  사용하지 않는 RegExp 속성을 참고하세요.

생성자

RegExp()
새로운 RegExp 객체를 생성합니다.

정적 속성

get RegExp[@@species]
파생 객체를 생성할 때 사용하는 생성자입니다.
RegExp.lastIndex
다음 판별을 시작할 인덱스입니다.

인스턴스 속성

RegExp.prototype.flags
RegExp 객체의 플래그를 담은 문자열입니다.
RegExp.prototype.dotAll
.이 줄 바꿈에 일치하는지 여부를 나타냅니다.
RegExp.prototype.global
정규 표현식이 문자열 내에서 가능한 모든 경우에 일치하는지, 아니면 최초에 대해서만 일치하는지 나타냅니다.
RegExp.prototype.ignoreCase
문자열의 대소문자를 구분하는지 나타냅니다.
RegExp.prototype.multiline
여러 줄에 걸쳐 탐색할 것인지 나타냅니다.
RegExp.prototype.source
패턴을 나타내는 문자열입니다.
RegExp.prototype.sticky
검색이 접착(sticky)되어있는지 나타냅니다.
RegExp.prototype.unicode
Unicode 기능의 활성화 여부입니다.

인스턴스 메서드

RegExp.prototype.compile()
스크립트 실행 중 정규 표현식을 (다시) 컴파일합니다.
RegExp.prototype.exec()
문자열 매개변수에 대해 검색을 실행합니다.
RegExp.prototype.test()
문자열 매개변수에 대해 판별을 실행합니다.
RegExp.prototype.toString()
객체의 문자열 표현을 반환합니다. Object.prototype.toString() 메서드를 재정의합니다.
RegExp.prototype[@@match]()
주어진 문자열에 대해 일치하는 결과를 반환합니다.
RegExp.prototype[@@matchAll]()
주어진 문자열에 대해 일치하는 모든 결과를 반환합니다.
RegExp.prototype[@@replace]()
주어진 문자열 내의 일치를 새로운 문자열로 대치합니다.
RegExp.prototype[@@search]()
주어진 문자열에 대해 일치하는 인덱스를 반환합니다.
RegExp.prototype[@@split]()
주어진 문자열을 분할해 배열로 반환합니다.

예제

정규 표현식을 사용해서 데이터 형식 바꾸기

다음 스크립트에서는 String 객체의 replace() 메서드를 사용하여 이름 성씨 형태의 이름을 성씨, 이름 형태 바꿔 반환합니다.

대치 문자열에는 $1$2를 사용하여 정규 표현식 패턴의 각 괄호에 일치한 결과를 받아옵니다.

let re = /(\w+)\s(\w+)/
let str = 'John Smith'
let newstr = str.replace(re, '$2, $1')
console.log(newstr)

실행 결과는 "Smith, John"입니다.

정규 표현식을 사용해서 여러 가지 줄 바꿈 문자가 있는 문자열 나누기

기본 줄 바꿈 문자는 플랫폼(Unix, Windows 등)마다 다릅니다. 아래의 분할 스크립트는 모든 플랫폼의 줄 바꿈을 인식합니다.

let text = 'Some text\nAnd some more\r\nAnd yet\rThis is the end'
let lines = text.split(/\r\n|\r|\n/)
console.log(lines) // logs [ 'Some text', 'And some more', 'And yet', 'This is the end' ]

정규 표현식 패턴의 순서를 바꾸면 작동하지 않을 수 있습니다.

여러 줄에서 정규 표현식 사용하기

let s = 'Please yes\nmake my day!'

s.match(/yes.*day/);
// Returns null

s.match(/yes[^]*day/);
// Returns ["yes\nmake my day"]

접착 플래그와 함께 사용하기

sticky 플래그는 해당 정규 표현식이 접착 판별, 즉 RegExp.prototype.lastIndex에서 시작하는 일치만 확인하도록 할 수 있습니다.

let str = '#foo#'
let regex = /foo/y

regex.lastIndex = 1
regex.test(str)      // true
regex.lastIndex = 5
regex.test(str)      // false (lastIndex is taken into account with sticky flag)
regex.lastIndex      // 0 (reset after match failure)

접착과 전역 플래그의 차이

접착 플래그 y의 일치는 정확히 lastIndex 위치에서만 발생할 수 있으나, 전역 플래그 g의 경우 lastIndex 또는 그 이후에서도 발생할 수 있습니다.

re = /\d/y;
while (r = re.exec("123 456")) console.log(r, "AND re.lastIndex", re.lastIndex);

// [ '1', index: 0, input: '123 456', groups: undefined ] AND re.lastIndex 1
// [ '2', index: 1, input: '123 456', groups: undefined ] AND re.lastIndex 2
// [ '3', index: 2, input: '123 456', groups: undefined ] AND re.lastIndex 3
//   ... and no more match.

전역 플래그 g를 사용했다면, 3개가 아니고 6개 숫자 모두 일치했을 것입니다.

정규 표현식과 Unicode 문자

 \w\Wa부터 z, A부터 Z, 0부터 9 _ 등의 ASCII 문자에만 일치합니다.

러시아어나 히브리어와 같은 다른 언어의 문자까지 일치하려면 \uhhhh(이때 hhhh는 해당 문자의 16진법 Unicode 값) 문법을 사용하세요. 아래 예제에서는 문자열에서 Unicode 문자를 추출합니다.

let text = 'Образец text на русском языке'
let regex = /[\u0400-\u04FF]+/g

let match = regex.exec(text)
console.log(match[0])        // logs 'Образец'
console.log(regex.lastIndex) // logs '7'

let match2 = regex.exec(text)
console.log(match2[0])       // logs 'на' [did not log 'text']
console.log(regex.lastIndex) // logs '15'

// and so on

유니코드 속성 이스케이프 기능을 사용해 \p{scx=Cyrl}과 같은 간단한 구문으로 이 문제를 해결할 수 있습니다.

URL에서 서브도메인 추출하기

let url = 'http://xxx.domain.com'
console.log(/[^.]+/.exec(url)[0].substr(7)) // logs 'xxx'

이 때는 정규표현식보단 URL API를 통해 브라우저에 내장된 URL 구문 분석기를 사용하는 것이 좋습니다.

명세

명세
ECMAScript (ECMA-262)
The definition of 'RegExp' in that specification.

브라우저 호환성

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
RegExpChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 4Opera Full support 5Safari Full support 1WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android Full support 1.0nodejs Full support Yes
RegExp() constructorChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 4Opera Full support 5Safari Full support 1WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android Full support 1.0nodejs Full support Yes
compile
Deprecated
Chrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 4Opera Full support 6Safari Full support 3.1WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 2Samsung Internet Android Full support 1.0nodejs Full support Yes
dotAllChrome Full support 62Edge Full support 79Firefox Full support 78IE No support NoOpera Full support 49Safari Full support 12WebView Android Full support 62Chrome Android Full support 62Firefox Android No support NoOpera Android Full support 46Safari iOS Full support 12Samsung Internet Android Full support 8.0nodejs Full support 8.10.0
Full support 8.10.0
Full support 8.3.0
Disabled
Disabled From version 8.3.0: this feature is behind the --harmony runtime flag.
execChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 4Opera Full support 5Safari Full support 1WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android Full support 1.0nodejs Full support Yes
flagsChrome Full support 49Edge Full support 79Firefox Full support 37IE No support NoOpera Full support 39Safari Full support 9WebView Android Full support 49Chrome Android Full support 49Firefox Android Full support 37Opera Android Full support 41Safari iOS Full support 9Samsung Internet Android Full support 5.0nodejs Full support 6.0.0
globalChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 5.5Opera Full support 5Safari Full support 1WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android Full support 1.0nodejs Full support Yes
ignoreCaseChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 5.5Opera Full support 5Safari Full support 1WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android Full support 1.0nodejs Full support Yes
RegExp.input ($_)
Non-standard
Chrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 5.5Opera Full support 15Safari Full support 3WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 14Safari iOS Full support 1Samsung Internet Android Full support 1.0nodejs Full support Yes
lastIndexChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 5.5Opera Full support 5Safari Full support 1WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android Full support 1.0nodejs Full support Yes
RegExp.lastMatch ($&)
Non-standard
Chrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 5.5Opera Full support 10.5Safari Full support 3WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 11Safari iOS Full support 1Samsung Internet Android Full support 1.0nodejs Full support Yes
RegExp.lastParen ($+)
Non-standard
Chrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 5.5Opera Full support 10.5Safari Full support 3WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 11Safari iOS Full support 1Samsung Internet Android Full support 1.0nodejs Full support Yes
RegExp.leftContext ($`)
Non-standard
Chrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 5.5Opera Full support 8Safari Full support 3WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android Full support 1.0nodejs Full support Yes
lookbehind assertions ((?<= ) and (?<! ))Chrome Full support 62Edge Full support 79Firefox Full support 78IE No support NoOpera Full support 49Safari No support NoWebView Android Full support 62Chrome Android Full support 62Firefox Android No support No
Notes
No support No
Notes
Notes See bug 1225665.
Opera Android Full support 46Safari iOS No support NoSamsung Internet Android Full support 8.0nodejs Full support 8.10.0
multilineChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 5.5Opera Full support 5Safari Full support 1WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android Full support 1.0nodejs Full support Yes
RegExp.$1-$9Chrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 4Opera Full support 5Safari Full support 1WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android Full support 1.0nodejs Full support Yes
Named capture groupsChrome Full support 64Edge Full support 79Firefox Full support 78IE No support NoOpera Full support 51Safari Full support 11.1WebView Android Full support 64Chrome Android Full support 64Firefox Android No support NoOpera Android Full support 47Safari iOS Full support 11.3Samsung Internet Android Full support 9.0nodejs Full support 10.0.0
Full support 10.0.0
Full support 8.3.0
Disabled
Disabled From version 8.3.0: this feature is behind the --harmony runtime flag.
Unicode property escapes (\p{...})Chrome Full support 64Edge Full support 79Firefox Full support 78IE No support NoOpera Full support 51Safari Full support 11.1WebView Android Full support 64Chrome Android Full support 64Firefox Android No support NoOpera Android Full support 47Safari iOS Full support 11.3Samsung Internet Android Full support 9.0nodejs Full support 10.0.0
Full support 10.0.0
Full support 8.3.0
Disabled
Disabled From version 8.3.0: this feature is behind the --harmony runtime flag.
RegExp.rightContext ($')
Non-standard
Chrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 5.5Opera Full support 8Safari Full support 3WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android Full support 1.0nodejs Full support Yes
sourceChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 4Opera Full support 5Safari Full support 1WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android Full support 1.0nodejs Full support Yes
stickyChrome Full support 49Edge Full support 13Firefox Full support 3IE No support NoOpera Full support 36Safari Full support 10WebView Android Full support 49Chrome Android Full support 49Firefox Android Full support 4Opera Android Full support 36Safari iOS Full support 10Samsung Internet Android Full support 5.0nodejs Full support Yes
testChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 4Opera Full support 5Safari Full support 1WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android Full support 1.0nodejs Full support Yes
toSource
Non-standard
Chrome No support NoEdge No support NoFirefox No support 1 — 74
Notes
No support 1 — 74
Notes
Notes Starting in Firefox 74, toSource() is no longer available for use by web content. It is still allowed for internal and privileged code.
IE No support NoOpera No support NoSafari No support NoWebView Android No support NoChrome Android No support NoFirefox Android Full support 4Opera Android No support NoSafari iOS No support NoSamsung Internet Android No support Nonodejs No support No
toStringChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 4Opera Full support 5Safari Full support 1WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android Full support 1.0nodejs Full support Yes
unicodeChrome Full support 50Edge Full support 12
Notes
Full support 12
Notes
Notes Case folding is implemented in version 13
Firefox Full support 46IE No support NoOpera Full support 37Safari Full support 10WebView Android Full support 50Chrome Android Full support 50Firefox Android Full support 46Opera Android Full support 37Safari iOS Full support 10Samsung Internet Android Full support 5.0nodejs Full support Yes
@@matchChrome Full support 50Edge Full support 13Firefox Full support 49IE No support NoOpera Full support 37Safari Full support 10WebView Android Full support 50Chrome Android Full support 50Firefox Android Full support 49Opera Android Full support 37Safari iOS Full support 10Samsung Internet Android Full support 5.0nodejs Full support 6.0.0
@@matchAllChrome Full support 73Edge Full support 79Firefox Full support 67IE No support NoOpera Full support 60Safari Full support 13WebView Android Full support 73Chrome Android Full support 73Firefox Android Full support 67Opera Android Full support 52Safari iOS Full support 13Samsung Internet Android Full support 5.0nodejs Full support 12.0.0
@@replaceChrome Full support 50Edge Full support 79Firefox Full support 49IE No support NoOpera Full support 37Safari Full support 10WebView Android Full support 50Chrome Android Full support 50Firefox Android Full support 49Opera Android Full support 37Safari iOS Full support 10Samsung Internet Android Full support 5.0nodejs Full support 6.0.0
@@searchChrome Full support 50Edge Full support 13Firefox Full support 49IE No support NoOpera Full support 37Safari Full support 10WebView Android Full support 50Chrome Android Full support 50Firefox Android Full support 49Opera Android Full support 37Safari iOS Full support 10Samsung Internet Android Full support 5.0nodejs Full support 6.0.0
@@speciesChrome Full support 50Edge Full support 13Firefox Full support 49IE No support NoOpera Full support 37Safari Full support 10WebView Android Full support 50Chrome Android Full support 50Firefox Android Full support 49Opera Android Full support 37Safari iOS Full support 10Samsung Internet Android Full support 5.0nodejs Full support 6.5.0
Full support 6.5.0
Full support 6.0.0
Disabled
Disabled From version 6.0.0: this feature is behind the --harmony runtime flag.
@@splitChrome Full support 50Edge Full support 79Firefox Full support 49IE No support NoOpera Full support 37Safari Full support 10WebView Android Full support 50Chrome Android Full support 50Firefox Android Full support 49Opera Android Full support 37Safari iOS Full support 10Samsung Internet Android Full support 5.0nodejs Full support 6.0.0

Legend

Full support  
Full support
No support  
No support
Non-standard. Expect poor cross-browser support.
Non-standard. Expect poor cross-browser support.
Deprecated. Not for use in new websites.
Deprecated. Not for use in new websites.
See implementation notes.
See implementation notes.
User must explicitly enable this feature.
User must explicitly enable this feature.

같이 보기