특정한 규칙을 가진 문자열의 집합을 표현하는 데 사용하는 형식 언어이다.
1. Regex 클래스의 생성자 이용
val regex = Regex("[0-9|a-z]")
2. String 클래스의 확장 함수인 toRegex() 이용
val regex ="[0-9|a-z]".toRegex()
3. 삼중 따옴표를 이용
val regex = """\([A-Z]\w+\)""".toRegex()
matchEntire()
val matchResult : MatchResult? = regex.matchEntire("abcd")
find()
val matchResult : MatchResult? = regex.find("abcd")
findAll()
val matchResult: Sequence<MatchResult> = regex.findAll("abcd")
1. 인터넷 주소
val path = "https://naver.com"
val regex = "https://(.+)".toRegex()
isMatch(path, regex)
fun isMatch(path: String, regex: Regex) {
if (path.matches(regex)) println("match")
else println("not match")
}
val path1 = "https://naver.com"
val path2 = "http://daum.net"
val path3 = "ftp://example.com"
val path4 = "telnet://abc.com"
val regex = "(https|http|ftp|telnet)://www\\.(.+)\\.(com|net)".toRegex()
// "https://" + "www" + "." + 문자열 + "." + 문자열의 형식
isMatch(path1, regex)
isMatch(path2, regex)
isMatch(path3, regex)
isMatch(path4, regex)
2. 파일 구조 확인
folder1/folder2/folder3/filename.java 와 같은 구조의 파일을 가져오려면
val regex = "(.+)/(.+)\\.(.+)".toRegex()
val path = "folder1/folder2/folder3/filename.java"
if (path.matches(regex)){
println("match!")
val res = regex.matchEntire(path)
if (res != null){
val (p, n, e) = res.destructured
println("$p, $n, $e")
}
}
else println("not match..")
3. IP 주소의 뒷자리 바꾸기
// 맨 뒤를 .1로 바꾸기
println( "192.168.0.125".replace("\\.\\d+$".toRegex(), ".1") )
// 모든 주소를 .x로 바꾸기
println( "192.168.0.125".replace("\\d+".toRegex(), "x") )
참조
https://keykat7.blogspot.com/2021/07/kotlin.html
https://yoon-dailylife.tistory.com/113