Java/Class & method
replace
sanghyeon
2022. 12. 20. 01:48
replace() : 특정 문자열을 지정한 문자 값으로 변환 해주는 메서드
public class Main {
public static void main(String[] args) {
String str = "HEllO";
System.out.println(str.replace("l","L")); // 타겟 "L" 변환 대상 "L"
//l이 L 로 변환 되어 "HELLO" 출력 됨
}
}
replaceFirst() : 특정 문자열 중 첫번째것 지정한 문자 값으로 변환 해주는 메서드
public class Main {
public static void main(String[] args) {
String str = "hello hello hello";
System.out.println(str.replaceFirst("hello","HELLO")); // 처음 hello 만 HELLO로 변환
}
}
replaceAll() : 정규표현식으로 변환이 가능한 메서드
public class Main {
public static void main(String[] args) {
String str = "abcd ABCD 가나다라 1234 !@#$";
System.out.println(str.replaceAll("[a-z]","")); // 타겟 정규식 "(영어)소문자" 변환 대상 ""
//모든 소문자 제거 후 출력
System.out.println(str.replaceAll("[A-Z]","")); // 타겟 정규식 "(영어)대문자" 변환 대상 ""
//모든 대문자 제거 후 출력
System.out.println(str.replaceAll("[A-z]","")); // 타겟 정규식 "(영어)모든문자" 변환 대상 ""
//모든 영문자 제거 후 출력
System.out.println(str.replaceAll("[\\uAC00-\\uD7A3]","")); // 타겟 정규식 "한국어" 변환 대상 ""
//모든 한국어 제거 후 출력(유니코드)
System.out.println(str.replaceAll("[0-9]","")); // 타겟 정규식 "모든숫자" 변환 대상 ""
//숫자가 전부 제거 후 출력 or \\d 로도 가능
System.out.println(str.replaceAll("[^0-9]","")); // 타겟 정규식 "숫자를 뺀 모두 " 변환 대상 ""
//숫자만 남기고 전부 제거 후 출력 or \\D 로도 가능
System.out.println(str.replaceAll("[\\s]","")); // 타겟 정규식 "공백 " 변환 대상 ""
//공백 제거 후 출력
System.out.println(str.replaceAll("[\\S]","")); // 타겟 정규식 "숫자를 뺀 모두 " 변환 대상 ""
//공백만 남기고 전부 제거 후 출력
System.out.println(str.replaceAll("[ab][c]","")); // 타겟 정규식 "a나b를 중에 c가 조합된 문자 " 변환 대상 ""
// bc 제거 후 출력
}
}
이외에도 다양한 정규식 들이 있다.(추후 추가 예정)