정규 표현식 혹은 정규식이라고 부른다.
특정 문자 조합을 찾기 위한 패턴으로 javascript에서는 정규 표현식을 객체로서 RegExp의 exec()와 test() 메서드를 사용할 수 있다.
String객체의 match(),matchAll(),replace(),replaceAll(),search(),split()매서드 사용가능
정규표현식 만들기
const aaa = /ab+c/
const re = new RegExp('ab+c')
정규 표현식 패턴 작성하기
x|y
: x또는 y와 매칭이 되는 경우
[xyz]
or [a-c]
: 문자 집합. 포함된 문자 중 하나와 일치합니다. 하이픈을 사용하여 문자 범위를 지정할 수 있지만, 하이픈이 대괄호 안에 포함된 첫 번째 또는 마지막 문자로 나타나면 문자 집합에 일반 문자로 포함되도록 리터럴 하이픈으로 간주됩니다. 문자 집합에 문자 클래스를 포함할 수도 있다.
const aaa = /[^a-bc]/
"basic".split(aaa) //[ 'ba', '', 'c' ]
"bacon".match(aaa) //[ 'o', index: 3, input: 'bacon', groups: undefined ]
(x) : 캡처 그룹: x와 일치하고 일치된 내용을 기억합니다. 예를 들어 /(foo)/는 "foo bar"의 "foo"와 일치하고 기억합니다.
/n:여기서 n은 양의 정수입니다. 정규식에서 괄호(왼쪽 괄호 포함)와 일치하는 마지막 하위 문자열에 대한 역참조입니다. 예를 들어 /apple( , )\sorange\1/는 "apple, orange, cherry, peach"의 "apple, orange"와 일치합니다. 다음 표에 완전한 예가 나와 있습니다.
\d : Matches any digit (Arabic numeral). Equivalent to [0-9]
. For example, /\\d/
or /[0-9]/
matches "2" in "B2 is the suite number".
\w :Matches any alphanumeric character from the basic Latin alphabet, including the underscore. Equivalent to [A-Za-z0-9_]
. For example, /\\w/
matches "a" in "apple", "5" in "$5.28", "3" in "3D" and "m" in "Émanuel".
수량자 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Quantifiers
정규식 만들어 보기
//들어오는 데이터 종류
//1S2D*3T , 1D2S#10S , 1D2S0T 등...
const dart = /\\d{1,2}[SDT]{1}[*|#]?/g;
출처 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes,
https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Regular_Expressions