이 문제 풀다가 정리해야겠다고 다짐함
String originalString = "Hello, World!";
String replacedString = originalString.replaceAll("World", "Java");
System.out.println(replacedString); // 출력: Hello, Java!
기본적으로 String클래스의 replaceAll("바꿀문자열패턴", "바뀔문자열내용") 을 사용하여 문자열 속 내용을 쉽게 바꿀수있다. 여기에 정규표현식을 활용한다면 문자열 내의 패턴을 찾기 간단해진다.
. : 어떤 문자 하나
^: 문자열의 시작( []안에서는 not의 의미인것을 주의)
$: 문자열의 끝
[]: 문자 클래스로, 괄호 안에 있는 문자 중 하나와 매치됨
|: OR 조건
[a-z]: 알파벳 소문자 중 하나와 매치
[0-9]: 숫자 중 하나와 매치
[^a-z]: 알파벳 소문자를 제외한 문자와 매치
*: 0번 이상 반복
+: 1번 이상 반복
?: 0 또는 1번의 반복
{n}: 정확히 n번 반복
{n,}: n번 이상 반복
{n,m}: n번 이상, m번 이하의 반복
\d : 숫자(digit)와 매치
\w : 문자(word)와 매치
\s : 공백과 매치
\b : 단어의 경계
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String text = "This is a sample text with email addresses such as john@example.com and alice123@example.co.uk. " +
"Please contact support@company.com for assistance.";
// 이메일 주소를 찾기 위한 정규표현식 패턴
String emailPattern = "\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b";
// 패턴에 대한 정규표현식 객체 생성
Pattern pattern = Pattern.compile(emailPattern);
Matcher matcher = pattern.matcher(text);
// 매칭된 이메일 주소 출력
while (matcher.find()) {
System.out.println("Found email address: " + matcher.group());
}
}
}
Found email address: john@example.com
Found email address: alice123@example.co.uk
Found email address: support@company.com
"\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b" 이걸 하나씩 해석해보자면,
\b를 맨 앞과 뒤에 붙여서 이메일주소 뒤에 다른 문자가 붙는 경우를 방지함
[A-Za-z0-9._%+-] : 알파벳이나 숫자나 . + % + - 기호찾기 = leesinyeoung98 같은 이메일의 앞부분
+@ : 그다음 @ 오고
[A-Za-z0-9.-] : 알파벳이나 ., - 찾기 = 이메일 도메인
+\\. 점찾기
[A-Za-z]{2,} : 최소 알파벳 두개반복찾기 = 최상위 도메인(com, net, io, kr)
public class Main {
public static void main(String[] args) {
// 예시 텍스트
String text = "This is a sample text with phone numbers such as 123-456-7890 and 987.654.3210.";
// 전화번호를 찾기 위한 정규표현식 패턴
String phonePattern = "\\b\\d{3}[-.]\\d{3}[-.]\\d{4}\\b";
// 패턴에 대한 정규표현식 객체 생성
Pattern pattern = Pattern.compile(phonePattern);
// 매칭된 전화번호를 "PHONE"으로 치환하여 출력
String replacedText = text.replaceAll(phonePattern, "PHONE");
System.out.println(replacedText);
}
}
알아두면 문자열 필터링 관련 문제는 날로먹겠쥬?