π™π™šπ™œπ™ͺ𝙑𝙖𝙧 𝙀𝙭π™₯π™§π™šπ™¨π™¨π™žπ™€π™£

uuuouuoΒ·2022λ…„ 7μ›” 21일
0
post-thumbnail

πŸ“– μ •κ·œν‘œν˜„μ‹


  • 컴퓨터 κ³Όν•™μ˜ μ •κ·œμ–Έμ–΄λ‘œλΆ€ν„° 유래
  • νŠΉμ •ν•œ κ·œμΉ™μ„ 가진 λ¬Έμžμ—΄μ˜ 집합을 ν‘œν˜„ν•˜κΈ° μœ„ν•΄ μ“°μ΄λŠ” ν˜•μ‹ μ–Έμ–΄
  • ν…μŠ€νŠΈ νŽΈμ§‘κΈ°λ‚˜ 슀크립트 μ–Έμ–΄μ—μ„œ λ¬Έμžμ—΄μ˜ 검색과 μΉ˜ν™˜μ„ μœ„ν•΄ 지원

πŸ’¬ 자주 μ‚¬μš©ν•˜λŠ” μ •κ·œ ν‘œν˜„μ‹


μ •κ·œν‘œν˜„μ‹μ„€λͺ…
^[0-9]*$숫자
^[a-zA-z]*$영문자
^[κ°€-힣]*$ν•œκΈ€
\\w+@\\w+\\.\\w+(\\.\\w+)?e-mail
^\d{2,3}-\d{3,4}-\d{4}$μ „ν™”λ²ˆν˜Έ
\d{6} \- [1-4]\d{6}μ£Όλ―Όλ“±λ‘λ²ˆν˜Έ
^\d{3}-\d{2}$우편번호

πŸ’¬ μ •κ·œν‘œν˜„μ‹ μž‘μ„±


  • java.util.regex νŒ¨ν‚€μ§€μ— μžˆλŠ” 클래슀 μ‚¬μš©
  • Pattern ν΄λž˜μŠ€μ™€ Matcher ν΄λž˜μŠ€κ°€ 있음

β—Ύ Pattern 클래슀

λ©”μ†Œλ“œμ„€λͺ…
static Pattern compile(String regex)μ „λ‹¬λœ μ •κ·œν‘œν˜„μ‹μœΌλ‘œλΆ€ν„° νŒ¨ν„΄ 생성
Matche matcher(CharSequence input)λŒ€μƒ λ¬Έμžμ—΄μ΄ νŒ¨ν„΄κ³Ό μΌμΉ˜ν•  경우 true λ°˜ν™˜
String pattern()μ •κ·œν‘œν˜„μ‹μ„ String ν˜•νƒœλ‘œ λ°˜ν™˜
Predicate< String > asPredicate()λ¬Έμžμ—΄μ„ μΌμΉ˜μ‹œν‚€λŠ” 데 μ‚¬μš©ν•  수 μžˆλŠ” μˆ μ–΄ μž‘μ„±
String[] split(CharSequence input)λ¬Έμžμ—΄μ„ 주어진 μΈμžκ°’ CharSequence νŒ¨ν„΄μ— 따라 뢄리

β—Ύ Matcher 클래슀

λ©”μ†Œλ“œμ„€λͺ…
boolean matches()λŒ€μƒ λ¬Έμžμ—΄κ³Ό νŒ¨ν„΄μ΄ μΌμΉ˜ν•˜λŠ” 경우 true λ°˜ν™˜
boolean find()λŒ€μƒ λ¬Έμžμ—΄κ³Ό νŒ¨ν„΄μ΄ μΌμΉ˜ν•˜λŠ” 경우 true λ°˜ν™˜ν•˜κ³  κ·Έ μœ„μΉ˜λ‘œ 이동
boolean find(int start)start 인자둜 받은 μœ„μΉ˜λΆ€ν„° 맀칭 체크
int start()λ§€μΉ­λ˜λŠ” λ¬Έμžμ—΄μ˜ μ‹œμž‘ μœ„μΉ˜λ₯Ό λ°˜ν™˜
int start(int group)μ§€μ •λœ 그룹이 λ§€μΉ­λ˜λŠ” μ‹œμž‘μœ„μΉ˜ λ°˜ν™˜
int end()λ§€μΉ­λ˜λŠ” λ¬Έμžμ—΄μ˜ 끝 λ°”λ‘œ λ‹€μŒ μœ„μΉ˜λ₯Ό λ°˜ν™˜
int end(int group)μ§€μ •λœ 그룹이 λ§€μΉ­λ˜λŠ” 끝 λ°”λ‘œ λ‹€μŒ 문자 μœ„μΉ˜λ₯Ό λ°˜ν™˜
String group()맀칭된 λΆ€λΆ„ λ°˜ν™˜
String group(int group)맀칭된 λΆ€λΆ„ 쀑 group번째 그루핑 맀칭뢀뢄을 λ°˜ν™˜
int groupCount()νŒ¨ν„΄λ‚΄ κ·Έλ£Ήν•‘ν•œ 전체 갯수λ₯Ό λ°˜ν™˜

πŸ’¬ μ‚¬μš© 예제


예제 1

import java.util.regex.*;

public class Example1 {
	public static void main(String[] args)  {
        Pattern pattern = Pattern.compile("^[0-9]*$"); // νŒ¨ν„΄ 생성
        String val = "123"; //λŒ€μƒλ¬Έμžμ—΄
	
        Matcher matcher = pattern.matcher(val);
        System.out.println(matcher.find()); // true
	}
}

예제 2

public class Example2 {
	public static void main(String[] args)  {
        Pattern pattern = Pattern.compile("^[0-9]*$"); // νŒ¨ν„΄ 생성
        
        System.out.println(num.matcher("12as").matches()); // false
	}
}

0개의 λŒ“κΈ€