[Java] replace() vs replaceAll()

Wish·2025년 2월 4일

Java

목록 보기
1/3

일반 문자열을 사용

public class StringEx1 {
	public static void main(String[] args) {
    	//replace()
        String str1 = "Hello World";
        String reStr1 = str1.replace("l", "L");
        
        System.out.println("str1 :" + str1);
        System.out.println("reStr1 :" + reStr1);
        
        //replaceAll()
        String str2 = "Hello World";
        String reStr2 = str2.replace("l", "L");
        
        System.out.println("str2 :" + str2);
        System.out.println("reStr2 :" + reStr2);    
    }
}
str1 : Hello World
reStr1 : HeLLo WorLd
str2 : Hello World
reStr2 : HeLLo WorLd

replace()와 replaceAll() 두 메소드 모두 특정 문자열을 새로운 문자열로 대체된 결과(String)을 반환한다.

Method설명
String replace(CharSequence old, CharSequence new)특정 문자열 중 old 문자열을 새로운 new 문자열로 모두 바꾼 문자열을 반환한다.
String replaceAll(String regex, String replacement)특정 문자열 중 지정된 문자열 regex와 일치하는 모든 문자를 새로운 문자열 replacemet로 변경한다.

replace()는 특정 문자열을 새로운 문자열로 대체하기 위한 메소드
replaceAll()은 특정한 정규식에 일치하는 문자열을 전부 다른 문자열로 대체하기 위한 메소드이다.

정규식을 사용

public class StringEx1 {
	public static void main(String[] args) {
    	//replace()
        String str1 = "helloworld에 오신 것을 welcome합니다~";
        String reStr1 = str1.replace("helloworld에", "").replace("welcome", "");
        
        System.out.println("str1 :" + str1);
        System.out.println("reStr1 :" + reStr1);
        
        //replaceAll()
        String str2 = "helloworld에 오신 것을 환영합니다~";
        String reStr2 = str2.replace("[a-z]", "");
        
        System.out.println("str2 :" + str2);
        System.out.println("reStr2 :" + reStr2);    
    }
}
str1 : helloworld에 오신 것을 welcome합니다~
reStr1 : 에 오신 것을 합니다~
str2 : helloworld에 오신 것을 welcome합니다~
reStr2 : 에 오신 것을 합니다~
  • String reStr1 = str1.replace("helloworld에", "").replace("welcome", "");
    문자열에서 "helloworld"를 공백으로 대체하고 그 결과값에서 "welcome"을 공백으로 대체한다.
  • String reStr2 = str2.replace("[a-z]", "");
    문자열에서 정규식에 일치하는 문자열을 공백으로 대체한다.
    [a-z]는 소문자 a to z를 나타내므로, 문자열에 존재하는 영 소문자를 모두 공백으로 대체한다.

    replace()는 특정 문자열을 대체할 때
    replaceAll()은 특정 패턴의 문자열을 대체할 때(영소문자 전체, 숫자 전체 등) 사용한다.

profile
원하는 것을 이뤄가는 중 🍀

0개의 댓글