정규 표현식이란 무엇인가?
정규식은 검색 패턴을 형성하는 일련의 문자이다.
텍스트에서 데이터를 검색할 때 이 검색 패턴을 사용하여 검색하는 내용을 설명할 수 있다.
정규식은 단일 문자이거나 더 복잡한 패턴일 수 있다.
정규식은 모든 유형의 텍스트 검색 및 텍스트 바꾸기 작업을 수행하는 데 사용할 수 있다.
/pattern/modifiers;
예시 해석:
/w3schools/i
는 정규식이다.
w3schools
는 패턴이다(검색에 사용됨).
i
는 수정자다(검색을 대소문자를 구분하지 않도록 수정).
JavaScript에서 정규식은 search()
및 replace()
의 두 가지 string 메서드
와 함께 자주 사용된다.
search()
메서드는 표현식(expression)을 사용하여 일치 항목을 검색하고 일치 항목의 위치를 반환한다.
replace()
메서드는 패턴이 대체된 수정된 문자열을 반환한다.
search()
메서드는 문자열에서 지정된 값을 검색하고 일치하는 위치를 반환한다.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>Search a string for "W3Schools", and display the position of the match:</p>
<p id="demo"></p>
<script>
let text = "Visit W3Schools!";
let n = text.search("W3Schools");
document.getElementById("demo").innerHTML = n;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Regular Expressions</h2>
<p>Search a string for "w3Schools", and display the position of the match:</p>
<p id="demo"></p>
<script>
let text = "Visit W3Schools!";
let n = text.search(/w3Schools/i);
document.getElementById("demo").innerHTML = n;
</script>
</body>
</html>
replace()
메서드는 지정된 값을 문자열의 다른 값으로 바꾼다.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>Replace "Microsoft" with "W3Schools" in the paragraph below:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit Microsoft!</p>
<script>
function myFunction() {
let text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML =
text.replace("Microsoft","W3Schools");
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>Replace "Microsoft" with "W3Schools" in the paragraph below:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit Microsoft!</p>
<script>
function myFunction() {
let text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML =
text.replace(/microsoft/i, "W3Schools");
}
</script>
</body>
</html>
위의 방법에서 문자열 인수 대신 정규식 인수를 사용할 수 있다.
정규식은 검색을 훨씬 더 강력하게 만들 수 있다(예: 대소문자 구분 안 함).
수정자
를 사용하여 대소문자를 구분하지 않는, 보다 전역적인 검색을 수행할 수 있다.
Modifier | Description | Try it |
---|---|---|
i | Perform case-insensitive matching | Try it |
g | Perform a global match (find all matches rather than stopping after the first match) | Try it |
m | Perform multiline matching | Tri it |
대괄호
는 문자 범위를 찾는 데 사용된다.
Expression | Description | Try it |
---|---|---|
[abc] | Find any of the characters between the brackets | Try it |
[0-9] | Find any of the digits between the brackets | Try it |
(x|y) | Find any of the alternatives separated with | | Try it |
메타
문자는 특별한 의미를 가진 문자다.
Metacharacter | Description | Try it |
---|---|---|
\ d | Find a digit | Try it |
\ s | Find a whitespace character | Try it |
\ b | Find a match at the beginning of a word like this: \ bWORD, or at the end of a word like this: WORD\ b | Try it, Try it |
\ uxxxx | Find the Unicode character specified by the hexadecimal number xxxx | Try it |
수량자
는 수량을 정의한다.
Quantifier | Description | Try it |
---|---|---|
n+ | Matches any string that contains at least one n | Try it |
n* | Matches any string that contains zero or more occurrences of n | Try it |
n? | Matches any string that contains zero or one occurrences of n | Try it |
JavaScript에서 RegExp 객체는 미리 정의된 속성 및 메서드가 있는 정규식 객체다.
test()
메서드는 RegExp 표현식 메서드다.
문자열에서 패턴을 검색하고 결과에 따라 true 또는 false를 반환한다.
다음 예시에서는 문자열에서 "e" 문자를 검색한다.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Regular Expressions</h2>
<p>Search for an "e" in the next paragraph:</p>
<p id="p01">The best things in life are free!</p>
<p id="demo"></p>
<script>
let text = document.getElementById("p01").innerHTML;
const pattern = /e/;
document.getElementById("demo").innerHTML = pattern.test(text);
</script>
</body>
</html>
정규 표현식을 변수에 먼저 넣을 필요는 없다. 위의 두 줄을 아래의 하나로 줄일 수 있다.
/e/.test("The best things in life are free!");
exec()
메소드는 RegExp 표현식 메소드다.
문자열에서 지정된 패턴을 검색하고 찾은 텍스트를 객체로 반환한다.
일치하는 항목이 없으면 빈(null) 객체를 반환한다.
다음 예시에서는 문자열에서 "e" 문자를 검색한다.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Regular Expressions</h2>
<p id="demo"></p>
<script>
const obj = /e/.exec("The best things in life are free!");
document.getElementById("demo").innerHTML =
"Found " + obj[0] + " in position " + obj.index + " in the text: " + obj.input;
</script>
</body>
</html>
완전한 참고를 원한다면, Complete JavaScript RegExp Reference. 를 참조하자.
참조에는 모든 RegExp 속성 및 메서드에 대한 설명과 예시가 포함되어 있다.