๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ

์ •๊ทœํ‘œํ˜„์‹

by Youcodein 2022. 8. 17.
728x90
๋ฐ˜์‘ํ˜•

 

์ •๊ทœ ํ‘œํ˜„์‹

์ •๊ทœ ํ‘œํ˜„์‹, ๋˜๋Š” ์ •๊ทœ์‹์€ ๋ฌธ์ž์—ด์—์„œ ํŠน์ • ๋ฌธ์ž ์กฐํ•ฉ์„ ์ฐพ๊ธฐ ์œ„ํ•œ ํŒจํ„ด์ž…๋‹ˆ๋‹ค.


์ •๊ทœ ํ‘œํ˜„์‹ ๊ฐ์ฒด ์ฃผ์š” ๋ฉ”์„œ๋“œ

์†์„ฑ ๊ฐ’ ์†์„ฑ ์„ค๋ช…
test() ์ •๊ทœ ํ‘œํ˜„์‹๊ณผ ์ผ์น˜ํ•˜๋Š” ๋ฌธ์ž์—ด์ด ์žˆ์œผ๋ฉด true, ์—†์œผ๋ฉด false๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
var reg =/Javascript/;
console.log(reg.test('Javascript')); //true
console.log(reg.test('script')); //false
match() ์ •๊ทœํ‘œํ˜„์‹๊ณผ ์ผ์น˜ํ•˜๋Š” ๋ฌธ์ž์—ด์„ ๋ฐฐ์—ด๋กœ ๋งŒ๋“ญ๋‹ˆ๋‹ค. ์ผ์น˜ํ•˜๋Š” ๋ฌธ์ž์—ด์ด ์—†์œผ๋ฉด null์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
var reg =/Javascript/;
str = 'Java script'
console.log(str.match('reg')); //null

์ •๊ทœ ํ‘œํ˜„์‹ ๊ฐ์ฒด ํ”Œ๋ž˜๊ทธ

ํ”Œ๋ž˜๊ทธ ์„ค๋ช…
i ๋Œ€์†Œ๋ฌธ์ž ๊ตฌ๋ถ„์—†์ด ์ •๊ทœํ‘œํ˜„์‹๊ณผ ๋ฌธ์ž์—ด์„ ๋น„๊ตํ•ฉ๋‹ˆ๋‹ค.
var reg1 =/javascript/;
var reg2 =/javascript/i;
var str = 'Javascript'
console.log(reg1.test(str)); //false
console.log(reg2.test(str)); //true
g ๋ฌธ์ž์—ด ์ „์ฒด๋ฅผ ์ •๊ทœํ‘œํ˜„์‹๊ณผ ๋น„๊ตํ•ฉ๋‹ˆ๋‹ค.
var reg1 =/a/;
var reg2 =/a/g;
var str = 'javascript'
console.log(str.match(reg 1)); //['a']
console.log(str.match(reg 2)); //['a','a']
m ์—ฌ๋Ÿฌ ํ–‰์˜ ๋ฌธ์ž์—ด์„ ์ •๊ทœํ‘œํ˜„์‹๊ณผ ๋น„๊ตํ•ฉ๋‹ˆ๋‹ค.
var reg1 =/^s/;
var reg2 =/^s/m;
var str = 'javas\ncript'
console.log(str.match(reg 1)); //null
console.log(str.match(reg 2)); //['s']

'^s'๋Š” ํ–‰์˜ ์ฒซ ๋ฒˆ์งธ ๋ฌธ์ž๊ฐ€ s๋กœ ์‹œ์ž‘ํ•˜๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•˜๊ณ  '\n'์€ ํ–‰ ๋ฐ”๊ฟˆ์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.

์ •๊ทœํ‘œํ˜„์‹ ๊ฐ์ฒด ์ฃผ์š” ํŒจํ„ด

ํŒจํ„ด ์„ค๋ช…
abc abc๋ฌธ์ž์—ด์„ ๊ฒ€์ƒ‰ํ•ฉ๋‹ˆ๋‹ค.
/abc/๋Š” 'abc'
[abc] a, b, c ์ค‘ ๋ฌธ์ž ํ•˜๋‚˜๋ฅผ ๊ฒ€์ƒ‰ํ•ฉ๋‹ˆ๋‹ค.
/[abc]d/๋Š” 'ad', 'bd', 'cd'
[^abc] a, b, c ๋ฅผ ์ œ์™ธํ•œ ๋ฌธ์ž ํ•˜๋‚˜๋ฅผ ๊ฒ€์ƒ‰ํ•ฉ๋‹ˆ๋‹ค.
/[^abc]d/๋Š” 'ed', 'fd', 'gd'
[A-Z] ์•ŒํŒŒ๋ฒณ ๋Œ€๋ฌธ์ž๋ฅผ ๊ฒ€์ƒ‰ํ•ฉ๋‹ˆ๋‹ค.
[a-z] ์•ŒํŒŒ๋ฒณ ์†Œ๋ฌธ์ž๋ฅผ ๊ฒ€์ƒ‰ํ•ฉ๋‹ˆ๋‹ค.
[0-9] 0-9๊นŒ์ง€์˜ ์ˆซ์ž๋ฅผ ๊ฒ€์ƒ‰ํ•ฉ๋‹ˆ๋‹ค
. ํ•˜๋‚˜์˜ ๋ฌธ์ž๋ฅผ ๊ฒ€์ƒ‰ํ•ฉ๋‹ˆ๋‹ค. ๋งŒ์•ฝ '๋งˆ์นจํ‘œ' ๋ฌธ์ž ๊ทธ๋Œ€๋กœ์˜ ์˜๋ฏธ๋ฅผ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ '\.'์œผ๋กœ ํ‘œํ˜„ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
\w ์•ŒํŒŒ๋ฒณ, ์ˆซ์ž, _๋ฅผ ๊ฒ€์ƒ‰ํ•ฉ๋‹ˆ๋‹ค.
\W ์•ŒํŒŒ๋ฒณ, ์ˆซ์ž, _๋ฅผ ์ œ์™ธํ•˜๊ณ  ๊ฒ€์ƒ‰ํ•ฉ๋‹ˆ๋‹ค.
\d ์ˆซ์ž๋ฅผ ๊ฒ€์ƒ‰ํ•ฉ๋‹ˆ๋‹ค.
\D ์ˆซ์ž๋ฅผ ์ œ์™ธํ•˜๊ณ  ๊ฒ€์ƒ‰ํ•ฉ๋‹ˆ๋‹ค.
\s ํ•˜๋‚˜์˜ ๊ณต๋ฐฑ์„ ๊ฒ€์ƒ‰ํ•ฉ๋‹ˆ๋‹ค.
\S ๊ณต๋ฐฑ์„ ์ œ์™ธํ•˜๊ณ  ๊ฒ€์ƒ‰ํ•ฉ๋‹ˆ๋‹ค.
^ ํ–‰์˜ ์ฒซ ๋ฌธ์ž๊ฐ€ ์ผ์น˜ํ•ด์•ผ ํ•จ์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.
$ ํ–‰์˜ ๋ ๋ฌธ์ž๊ฐ€ ์ผ์น˜ํ•ด์•ผ ํ•จ์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.
* * ์•ž์˜ ๋ฌธ์ž๊ฐ€ 0๋ฒˆ ์ด์ƒ ๋ฐ˜๋ณต์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.
/a*b/๋Š” 'b''ab''aab''aaab''aaaa...b'
+ + ์•ž์˜ ๋ฌธ์ž๊ฐ€ 1๋ฒˆ ์ด์ƒ ๋ฐ˜๋ณต์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.
/a+b/๋Š” 'ab''aab''aaab''aaaa...b'
? ? ์•ž์˜ ๋ฌธ์ž๊ฐ€01๋ฒˆ ๋˜๋Š” 1๋ฒˆ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.
/a?b/๋Š” 'b' 'ab'
{} /\d{3}/์€ ์ˆซ์ž 3๊ฐœ๋ฅผ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.
/\d{3,5}/์€ ์ˆซ์ž 3~5๊ฐœ๋ฅผ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.
/\d{3,}/์€ ์ˆซ์ž 3๊ฐœ ์ด์ƒ์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.
a|b a or b๋ฅผ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.
(abc) ๊ทธ๋ฃนํ™”๋ฅผ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.
728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€