STUDY/Java
정규식 표현 & 패턴 정리
개발하는 멍발자
2022. 4. 28. 14:27
상태전환: 데이터에 따라 상태가 바뀌는 것이다.
FRAC = 소수부분을 나타내는 fraction의 약어다.
문자에 대한 정규식
.(점) = 무엇이든지 한글자
[] = 어떤 문자, 범위 지정 가능
| = 어떤 표현
\(역슬래쉬) = 기능을 상쇄함, Java 문자열에서 \\
() = 그룹화
^ = 행 앞부분
$ = 행 끝 부분
출현 횟수에 대한 정규식
? = 존재하지 않습니까?
* = 여러번 반복, 없어도 가능함
+ = 여러번 반복, 하나는 필요함
앞뒤 부분 일치 정규식
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 앞/뒤/부분 일치 정규식
*/
public class ExamRegex2 {
public static void main(String[] args) {
String s = "000012-345-6789";
Pattern p = Pattern.compile(".*\\d{2,4}-\\d{2,4}-\\d{4}.*"); // 부분일치
//Pattern p = Pattern.compile(".*\\d{2,4}-\\d{2,4}-\\d{4}"); //뒷부분 일치
//Pattern p = Pattern.compile("\\d{2,4}-\\d{2,4}-\\d{4}"); //앞부분 일치
Matcher m = p.matcher(s);
System.out.println(m.find());
}
}
은행 계좌 카드 만들 때 번호 정규화
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
* 앞/뒤/부분 일치 정규식
*/
public class ExamRegex2 {
public static void main(String[] args) {
String s = "000012-345-6789";
//Pattern p = Pattern.compile(".*\\d{2,4}-\\d{2,4}-\\d{4}.*"); // 부분 일치
Pattern p = Pattern.compile(".*\\d{2,4}-\\d{2,4}-\\d{4}"); // 뒷부분 일치
//Pattern p = Pattern.compile(".\\d{2,4}-\\d{2,4}-\\d{4}"); // 앞부분 일치
Matcher m = p.matcher(s);
System.out.println(m.find());
}
}
전화번호 정규화
import java.util.regex.Pattern;
public class ExamRegex2 {
public static void main(String[] args) {
var s = "휴대폰은 010-222-0000입니다. 집전화는 031-123-4567입니다.";
var ptn = Pattern.compile("(\\d{2,4})-(\\d{2,4})-(\\d{4})");
var match = ptn.matcher(s);
while (match.find()) {
System.out.println("시작위치: " + match.start());
System.out.println("종료위치: " + match.end());
System.out.println("매칭문자열: " + match.group());
System.out.println("앞자리번호 : " + match.group(1));
System.out.println("중간번호: " + match.group(2));
System.out.println("끝자리번호: " + match.group(3));
}
}
}
//결과
시작위치: 5
종료위치: 17
매칭문자열: 010-222-0000
앞자리번호 : 010
중간번호: 222
끝자리번호: 0000
대소문자 구분 없이 처리하는 정규식
CASE_INSENSITIVE
import java.util.regex.Pattern;
public class ExamRegex4 {
/**
* 대소문자 구분 없이 처리하는 정규식
* CASE_INSENSITIVE
*/
public static void main(String[] args) {
var s = "업무용 이메일은 test^@exam.ccm입니다. 개인용 이메일은 TEST@exam.com입니다.";
var ptn = Pattern.compile("[a-z0-9.!#$%&'*+/=?^_{|}~-]+@[a-z0-9-]+(\\.[a-z0-9-]+)*", Pattern.CASE_INSENSITIVE);
var match = ptn.matcher(s);
while(match.find()) {
System.out.println(match.group());
}
}
}
//결과
test^@exam.ccm
TEST@exam.com
구분하여 출력 패턴
import java.util.regex.Pattern;
/**
* 구분하여 출력 패턴
*/
public class ExamRegex6 {
public static void main(String[] args) {
var s = "보고싶다\n보고싶다\n보고싶다\nYES";
var ptn = Pattern.compile("^.+", Pattern.DOTALL);
var match = ptn.matcher(s);
while(match.find()) {
System.out.println(match.group());
}
}
}
여러줄 패턴 검색시 사용
import java.util.regex.Pattern;
/**
* 여러줄 패턴검색시 사용
*/
public class ExamRegex5 {
public static void main(String[] args) {
var s = "1학년이 되면 친구\n100명을 사귈 수 있을까?\n";
var ptn = Pattern.compile("^\\d*", Pattern.MULTILINE);
var match = ptn.matcher(s);
while (match.find()) {
System.out.println(match.group()); // 1 100
}
}
HTML 태그만 분리하는 패턴
import java.util.regex.Pattern;
/**
* HTML태그만 분리하는 패턴
*/
public class ExamRegex7 {
public static void main(String[] args) {
var tags = "<p><strong>회원</strong>사이트링크<a href='index.html'><img src='member.jpg' /></a></p>";
var ptn = Pattern.compile("<.+?>");
var match = ptn.matcher(tags);
while(match.find()) {
System.out.println(match.group());
}
}
}
그룹을 이름으로 캡처하는 패턴
import java.util.regex.Pattern;
/**
* HTML태그만 분리하는 패턴
*/
public class ExamRegex7 {
public static void main(String[] args) {
var tags = "<p><strong>회원</strong>사이트링크<a href='index.html'><img src='member.jpg' /></a></p>";
var ptn = Pattern.compile("<.+?>");
var match = ptn.matcher(tags);
while(match.find()) {
System.out.println(match.group());
}
}
}
매치 언매치
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExamRegex9 {
public static void main(String[] args) {
String s1 = "My name is <div>Sage</div>";
String s2 = "I am a <span>Human</span>";
String s3 = "<span>Hello World</div>";
String regex = "<(div|span)>.*?<\\/\\1>";
Pattern p = Pattern.compile(regex);
System.out.println("패턴: "+ regex);
check(p, s1);
check(p, s2);
check(p, s3);
}
private static void check(Pattern p, String target) {
Matcher m = p.matcher(target);
if(m.find()) {
System.out.println("Match! " + target);
} else {
System.out.println("Unmatch! " + target);
}
}
}
이전문자열과 마지막 문자열 유무와 일치 판단 패턴
import java.util.regex.Pattern;
/**
* 이전문자열과 마지막문자열 유무와 일치 판단 패턴
* - A(?=B): B -> A 바로뒤를 따르는 경우에만 A와 일치
* - A(?!B) -> A가 바로 뒤따르지 않는 경우에만 A와 일치
* - (?<=B)A -> A바로 앞에 B가 있는경우에만 A와 일치
* - (?<!B)A -> A직전에 B가 없는 경우에만 A와 일치
*/
public class ExamRegex10 {
public static void main(String[] args) {
var r1 = Pattern.compile("우리(?=예)");
var r2 = Pattern.compile("우리(?!예)");
var r3 = Pattern.compile("(?<=x)우리");
var r4 = Pattern.compile("(?<!x)우리");
var s1 = "우리는 인간이다x";
var s2 = "우리는 과일입니다x 우리는 아무것도 없다x";
match(r1, s1);
match(r1, s2);
match(r2, s1);
match(r2, s2);
match(r3, s1);
match(r3, s2);
match(r4, s1);
match(r4, s2);
}
private static void match(Pattern ptn, String input) {
var match = ptn.matcher(input);
while(match.find()) {
System.out.println(match.group());
}
System.out.println("======");
}
}
문자열 대체 replaceAll 메소드
/**
* 문자열 대체
* replaceAll 메소드
*/
public class ExamRegex11 {
public static void main(String[] args) {
var s = "문의는 여기 https://devbro.xn--xyz-ky7m 해주세요.";
System.out.println(s.replaceAll("(?i)http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\\\w ./?%&=-]*)?",
"<a href=\"$0\">$0</a>"));
}
}
public class ExamRegex12 {
public static void main(String[] args) {
String s = "abc$de@fgh0ijk^lmn";
String[] s2 = s.split("[^a-zA-Z]");
for(String str : s2) {
System.out.println(str);
}
}
}
public class ExamRegex13 {
public static void main(String[] args) {
String s = "010-1111-2222";
String[] s2 = s.split("-");
for(String str: s2) {
System.out.print(str);
}
}
import java.util.Arrays;
public class ExamRegex14 {
public static void main(String[] args) {
String s = "jfslj47924fjslk24729djldja492824";
String regex = "[0-9]+";
System.out.println(Arrays.toString(s.split(regex)));
}
}
소수점 판단 패턴
/**
* 소수점 판단 패턴
* \\d+ => 숫자 다수
* \\.
* (\\.\\d+)? =>괄호안에 0개 또는 1개
*/
public class ExamRegex15 {
public static void main(String[] args) {
String s = "12.5";
String regex = "\\d+(\\.\\d+)?";
if(s.matches(regex)) {
System.out.println(Double.parseDouble(s));
} else {
System.out.println("double아님!");
}
}
}
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class ExamRegex16 {
public static void main(String[] args) {
String s = "2022-05-01";
String regex = "\\d{4}\\-\\d{2}\\-\\d{2}";
if(s.matches(regex)) {
try {
System.out.println(new SimpleDateFormat("yyyy-MM-dd").parse(s));
} catch (ParseException e) {
e.printStackTrace();
}
} else {
System.out.println("날짜 아님!");
}
}
}