알고리즘

[javascript] 정규식

NickTop 2023. 6. 22. 01:21

객체 만들기

const pattern = "\d+";
const flags = "gm";

const regexp = new RegExp(pattern, flags);

// 또는

const regexp2 = /\d+/gm;

 

메서드

flag :

i : 대소문자무시

g: 모두 반환 (아래 예시보면 쉬움)

m: 줄바꿈 인식 (앵커 ^ $ 가 각 줄별로 대응됨 밑에 정규식 패턴 참고)

match : 정규식에 맞는 값을 배열로 반환

const str = 'a1a2a3a4';

const regexp = /a\d/g;
const regexp2 = /a\d/;
const regexp3 = /a(\d)/g;
const regexp4 = /a(\d)/;

console.log(str.match(regexp));
console.log(str.match(regexp2));
console.log(str.match(regexp3));
console.log(str.match(regexp4));
console.log([...str.matchAll(regexp3)]);


// > Array ["a1", "a2", "a3", "a4"]
// > Array ["a1"]
// > Array ["a1", "a2", "a3", "a4"]
// > Array ["a1", "1"]
// > Array [Array ["a1", "1"], Array ["a2", "2"], Array ["a3", "3"], Array ["a4", "4"]]

g 플래그가 있으면 그룹()을 무시함, 그룹을 포함시키고  g 플래그를 쓰고 싶으면 matchAll

 

replace : 문자 변환

const p = 'I like dogs. Dogs are usually smarter than cats';

const regex = /dog/ig;
const regex2 = /dog/;
console.log(p.replace(regex, 'ferret'));
console.log(p.replace(regex2, 'ferret'));

// > "I like ferrets. ferrets are usually smarter than cats"
// > "I like ferrets. Dogs are usually smarter than cats"

 

split : 문자 나누기

const str = 'Hello...World......JavaScript';
const regex = /\.+/;
const regex2 = /(\.+)\./;
console.log(str.split(regex));
console.log(str.split(regex2));

// > Array ["Hello", "World", "JavaScript"]
// > Array ["Hello", "..", "World", ".....", "JavaScript"]

그룹화를 시키지 않으면 배열에서 없어짐

배열로 포함시키고 싶은 부분은 그룹화() 해야함

 

정규식 패턴

\d 숫자
\s 공백 (탭, 스페이스 등)
[] 괄호안의 표현 중 한 개
- 표현식 : [abc]
abcwef
dbaceg
^ 시작할 때만 체크
- 표현식 : ^[abc]
abcwef
dbaceg     /////  b가 있지만 b로 시작하지 않으므로 제외됨
$ 끝날 때만 체크
- 표현식 : c$
abcwef     /////  c가 있지만 c로 끝나지 않으므로 제외됨
dbac
[^문자] 문자 제외
- 표현식 : [^a]bc    /////  a제외한 아무 문자 + bc
abcd
bbcd
? 포함할 수도있고 없을수도 있음
- 표현식 : a?bc     /////  a를 포함할수도 안할수도 있음
abcwef
dbbceg
+ 한개 또는 여러개
- 표현식 : [ab]+
abbbabbcfwer
amnikpomnio
* 0개 또는 여러개
- 표현식 : abc*     /////  ab는 무조건 포함, c는 0개 또는 여러개 올 수 있음
cfweabbbabbcfwer
abcccccnikpomnio
- 범위지정
- 표현식 : [0-9a]     /////  0,1,2,3,4,5,6,7,8,9,a 중 하나
- 표현식 : [0-9a-z]     /////  0,1,2,3,4,5,6,7,8,9 또는 영어 소문자 중 하나
() 그룹 (그룹 패턴 따로 있음, 다루지는 않겠음)
{,} 반복
- 표현식 : [0-9]{2,4}
153214525
- 표현식 : [0-9]{2} : 2개만
- 표현식 : [0-9]{2,} : 최소 2개

 

예제

1. 분자식 split

const regex = /([A-Z][a-z]?|\d+|\(|\))/g;
const str = "Mg8Ca8(UO2)24(CO3)30O4(OH)12(H2O)138";
console.log(str.match(regex));

// > Array ["Mg", "8", "Ca", "8", "(", "U", "O", "2", ")", "24", "(", "C", "O", "3", ")", "30", "O", "4", "(", "O", "H", ")", "12", "(", "H", "2", "O", ")", "138"]

2. html 태그 제거

const regex = /<[^>]+>/g;
const txt = `<p>In contrast, <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match"><code>String.prototype.match()</code></a> method returns all matches at once, but without their position.</p>`;
const a = txt.replace(regex, "");
console.log(a);

// > "In contrast, String.prototype.match() method returns all matches at once, but without their position."

 

3. 강조하고 싶은 단어 진하게

e.g) 매칭되는 단어에 strong 태그 추가

const regex = /(dogs?)/ig;
const txt = `Dogs are cute, but some dogs are stubborn. I like my dog`;
const a = txt.replace(regex, "<strong>$1</strong>");
console.log(a);

// > "<strong>Dogs</strong> are cute, but some <strong>dogs</strong> are stubborn. I like my <strong>dog</strong>"

 

 

 

참고 및 도움되는 사이트)

https://regexone.com/

 

RegexOne - Learn Regular Expressions - Lesson 1: An Introduction, and the ABCs

Regular expressions are extremely useful in extracting information from text such as code, log files, spreadsheets, or even documents. And while there is a lot of theory behind formal languages, the following lessons and examples will explore the more prac

regexone.com

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions

 

Regular expressions - JavaScript | MDN

Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec() and test() methods of RegExp, and with the match(), matchAll(), replace(), replac

developer.mozilla.org