๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Basics/Develop

JAVA Pattern๊ณผ Matcher๋กœ ์ •๊ทœํ‘œํ˜„์‹ (์ „ํ™”๋ฒˆํ˜ธ ๋‚ ์งœ ๋“ฑ) ํฌ๋งท ์ฒดํฌํ•˜๊ธฐ ๊ฐœ๋ฐœ ์ˆœ์„œ์™€ ์ฝ”๋“œ

by IworldT 2022. 5. 4.
๋ฐ˜์‘ํ˜•

 

Java์—์„œ ๋ฐ์ดํ„ฐ ๊ฐ’์˜ format ํฌ๋งท์„ ์ฒดํฌํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ์•Œ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

 

์ž๋ฐ”์—์„œ ๋ฐ์ดํ„ฐ format validation์—๋Š” ๋‹ค์–‘ํ•œ ๋ฐฉ๋ฒ•์ด ์กด์žฌํ•˜์ง€๋งŒ,

์ด๋ฒˆ ํฌ์ŠคํŒ…์—์„œ๋Š” ๊ทธ ์ค‘์—์„œ๋„ java.util.regex.Matcher ์™€ java.util.regex.Pattern์„ ํ™œ์šฉํ•œ ์˜ˆ์ œ ์ฝ”๋“œ๋ฅผ ์ •๋ฆฌ ํ•ด ๋ณด๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.

 

์ž๋ฐ” ์ •๊ทœ ํ‘œํ˜„์‹ ์‚ฌ์šฉ ์ฝ”๋“œ ์˜ˆ์ œ

 


JAVA๋กœ Format Check ํ•˜๊ธฐ - regex

1. regex ํŒจํ‚ค์ง€ import ํ•˜๊ธฐ

...
import java.util.regex.Matcher;
import java.util.regex.Pattern;
...

 

์ด๋ฒˆ ํฌ์ŠคํŒ…์—์„œ ์‚ฌ์šฉํ•  ๋‘ ๊ฐ€์ง€ regex ํŒจํ‚ค์ง€๋ฅผ import ํ•ฉ๋‹ˆ๋‹ค.

์ž๋ฐ”์—์„œ๋Š” ์ •๊ทœํ‘œํ˜„์‹์„ ์‚ฌ์šฉํ•  ๋•Œ ๋ณดํ†ต ์ด ํŒจํ‚ค์ง€๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.

 

 

2. ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ƒ๊ฐํ•˜๊ธฐ

์ œ๊ฐ€ ์ƒ๊ฐํ•œ ์•Œ๊ณ ๋ฆฌ์ฆ˜์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค. 

์–ด๋– ํ•œ input ์ด ์žˆ์—ˆ์„ ๋•Œ, ๊ทธ format์˜ type์„ ๋ฐ›์Šต๋‹ˆ๋‹ค.

๊ทธ๋ฆฌ๊ณ  ๊ทธ type์— ๋”ฐ๋ผ์„œ format์˜ ์ •๊ทœํ‘œํ˜„์‹์„ ์ง€์ •ํ•ด์ค๋‹ˆ๋‹ค.

 

input -> ์ „ํ™”๋ฒˆํ˜ธ type ์ผ ๊ฒฝ์šฐ -> ์ „ํ™”๋ฒˆํ˜ธ ์ •๊ทœํ‘œํ˜„์‹์„ ๋„˜๊ฒจ์คŒ -> Matchํ•˜๋Š”์ง€ check

 

๋กœ ์ •๋ฆฌํ•  ์ˆ˜ ์žˆ๊ฒ ์Šต๋‹ˆ๋‹ค.

 

 

3. ์ •๊ทœ ํ‘œํ˜„์‹ ํ™•์ธํ•˜๊ธฐ

์ˆซ์ž - [0-9] ๋˜๋Š” \d

์˜์–ด - [a-zA-Z] ๋˜๋Š” \w

ํ•œ๊ธ€ - [๊ฐ€-ํžฃ]

[ ] ๋Š” ๊ทธ ์•ˆ์— ์žˆ๋Š” ๋ฌธ์ž ์ค‘ ํ•œ ๊ฐœ ๋งŒ์„ ๊ณ ๋ฅธ๋‹ค๋Š” ๋œป์ž…๋‹ˆ๋‹ค.
์—ฌ๋Ÿฌ๊ฐœ๋ฅผ ๊ณ ๋ฅด๋ ค๋ฉด ์˜ค๋ฅธํŽธ์— ์ž๋ฆฟ์ˆ˜๋ฅผ ์ถ”๊ฐ€ํ•ด์ค๋‹ˆ๋‹ค

์ž๋ฆฟ์ˆ˜ - {์ˆซ์ž}

ํ‘œํ˜„์‹์ด ์•„๋‹Œ, ์ผ๋ฐ˜ ๋ฌธ์ž๋กœ ์ทจ๊ธ‰ํ•˜๋Š” ๋ฒ• - \\ ๋’ค์— ์ž‘์„ฑ

 

์ž์ฃผ ์“ฐ์ด๋Š” ์ •๊ทœ ํ‘œํ˜„์‹

Email
\\w+@\\w+\\.\\w+(\\.\\w+)?
๋˜๋Š”
^[a-zA-Z0-9]+@[a-zA-Z0-9]+\\.[a-z]+$

ํœด๋Œ€ํฐ ๋ฒˆํ˜ธ
^01(?:0|1|[6-9])-(?:\\d{3}|\\d{4})-\\d{4}$

์ „ํ™” ๋ฒˆํ˜ธ
^(01[016789]{1}|02|0[3-9]{1}[0-9]{1})([0-9]{3,4})([0-9]{4})$

๋‚ ์งœ, ์ƒ๋…„์›”์ผ (8์ž๋ฆฌ)
(19|20)\\d{2}(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])

 

 

4. ์ฝ”๋“œ ์ž‘์„ฑํ•˜๊ธฐ

	boolean check = false;
	String regex = "";
		
	switch (format) {
	case "yyyymmddhhmiss":
		regex = "(19|20)\\d{2}(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])(0[0-9]|1[0-9]|2[0-3])([0-5][0-9])([0-5][0-9])";
		break;
	case "yyyymmdd":
		regex = "(19|20)\\d{2}(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])";
		break;
	case "phone":
		regex = "^01(?:0|1|[6-9])(\\d{3}|\\d{4})(\\d{4})$";
		break;
	case "tel":
		regex = "^(01[016789]{1}|02|0[3-9]{1}[0-9]{1})([0-9]{3,4})([0-9]{4})$";
		break;
	default:
		break;
	}
		
	if (!"".equals(regex)) {
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(txt);
			
		check = matcher.find();
	}

 

check๋Š” true ๋˜๋Š” false๋กœ ๋ฐ˜ํ™˜๋ฉ๋‹ˆ๋‹ค.

 


 

์ด๋ฒˆ ํฌ์ŠคํŒ…์€ ์ด๋ ‡๊ฒŒ ๊ฐ„๋‹จํžˆ ์ •๊ทœํ‘œํ˜„์‹์„ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•๊ณผ ์ฝ”๋“œ ์ž‘์„ฑ ์˜ˆ์ œ๋ฅผ ์‚ดํŽด๋ณด์•˜์Šต๋‹ˆ๋‹ค.

์ •๊ทœ ํ‘œํ˜„์‹ ๋ฌธ๋ฒ•์„ ๋”ฐ๋กœ ๊ณต๋ถ€ํ•˜์‹œ๋ฉด ๋‹ค์–‘ํ•œ format ์…‹ํŒ… ์‘์šฉ์ด ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€