JavaScript Tutorial.50

ansunny1170·2022년 1월 5일
0
post-thumbnail

JS Regular Expressions

What Is a Regular Expression?

정규 표현식이란 무엇인가?
정규식은 검색 패턴을 형성하는 일련의 문자이다.

텍스트에서 데이터를 검색할 때 이 검색 패턴을 사용하여 검색하는 내용을 설명할 수 있다.

정규식은 단일 문자이거나 더 복잡한 패턴일 수 있다.

정규식은 모든 유형의 텍스트 검색텍스트 바꾸기 작업을 수행하는 데 사용할 수 있다.

Syntax

/pattern/modifiers;


예시 해석:
/w3schools/i는 정규식이다.
w3schools는 패턴이다(검색에 사용됨).
i는 수정자다(검색을 대소문자를 구분하지 않도록 수정).

Using String Methods

JavaScript에서 정규식은 search()replace()의 두 가지 string 메서드와 함께 자주 사용된다.

search() 메서드는 표현식(expression)을 사용하여 일치 항목을 검색하고 일치 항목의 위치를 반환한다.

replace() 메서드는 패턴이 대체된 수정된 문자열을 반환한다.

Using String search() With a String

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>

Using String search() With a Regular Expression

<!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>

Using String replace() With a String

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>

Use String replace() With a Regular Expression

<!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>

Did You Notice?

위의 방법에서 문자열 인수 대신 정규식 인수를 사용할 수 있다.
정규식은 검색을 훨씬 더 강력하게 만들 수 있다(예: 대소문자 구분 안 함).

Regular Expression Modifiers

수정자를 사용하여 대소문자를 구분하지 않는, 보다 전역적인 검색을 수행할 수 있다.

ModifierDescriptionTry it
iPerform case-insensitive matchingTry it
gPerform a global match (find all matches rather than stopping after the first match)Try it
mPerform multiline matchingTri it

Regular Expression Patterns

대괄호는 문자 범위를 찾는 데 사용된다.

ExpressionDescriptionTry it
[abc]Find any of the characters between the bracketsTry it
[0-9]Find any of the digits between the bracketsTry it
(x|y)Find any of the alternatives separated with |Try it

메타 문자는 특별한 의미를 가진 문자다.

MetacharacterDescriptionTry it
\dFind a digitTry it
\sFind a whitespace characterTry it
\bFind a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\bTry it, Try it
\uxxxxFind the Unicode character specified by the hexadecimal number xxxxTry it

수량자는 수량을 정의한다.

QuantifierDescriptionTry it
n+Matches any string that contains at least one nTry it
n*Matches any string that contains zero or more occurrences of nTry it
n?Matches any string that contains zero or one occurrences of nTry it

Using the RegExp Object

JavaScript에서 RegExp 객체는 미리 정의된 속성 및 메서드가 있는 정규식 객체다.

Using test()

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!");

Using exec()

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 RegExp Reference

완전한 참고를 원한다면, Complete JavaScript RegExp Reference. 를 참조하자.
참조에는 모든 RegExp 속성 및 메서드에 대한 설명과 예시가 포함되어 있다.

profile
공정 설비 개발/연구원에서 웹 서비스 개발자로 경력 이전하였습니다. Node.js 백엔드 기반 풀스택 개발자를 목표로 하고 있습니다.

0개의 댓글