반응형

🎯 이 글에서 배우는 것: 문자열 조작, 검색, 치환, 정규표현식 기초
🔤 문자열이란?
프로그래밍에서 문자열(String)은 텍스트 데이터를 말합니다. AutoHotkey에서 문자열 처리는 핫스트링, 파일 처리, 클립보드 조작 등 거의 모든 작업에서 필수입니다!
text := "Hello, AutoHotkey!"
name := '홍길동' ; 작은따옴표도 OK
📏 기본 문자열 함수
StrLen - 문자열 길이
text := "안녕하세요"
length := StrLen(text)
MsgBox("길이: " length) ; 5
SubStr - 부분 문자열 추출
text := "AutoHotkey"
; SubStr(문자열, 시작위치, 길이)
MsgBox(SubStr(text, 1, 4)) ; "Auto" (1번째부터 4글자)
MsgBox(SubStr(text, 5)) ; "Hotkey" (5번째부터 끝까지)
MsgBox(SubStr(text, -3)) ; "key" (뒤에서 3글자)
MsgBox(SubStr(text, 1, -3)) ; "AutoHot" (끝에서 3글자 제외)
실용 예제: 파일 확장자 추출
filename := "document.pdf"
ext := SubStr(filename, -3) ; "pdf"
; 또는 더 안전하게
dotPos := InStr(filename, ".", -1) ; 마지막 점 위치
ext := SubStr(filename, dotPos + 1)
MsgBox("확장자: " ext)
🔍 문자열 검색
InStr - 문자열 찾기
text := "Hello World Hello"
; InStr(건초더미, 바늘, 대소문자구분, 시작위치, 발생횟수)
pos := InStr(text, "World") ; 7 (World의 시작 위치)
pos := InStr(text, "world") ; 0 (못 찾음 - 대소문자 구분)
pos := InStr(text, "world",, 0) ; 7 (대소문자 무시: 0 또는 false)
; 두 번째 "Hello" 찾기
pos := InStr(text, "Hello",,, 2) ; 13
; 뒤에서부터 찾기 (시작위치를 -1로)
pos := InStr(text, "Hello",, -1) ; 13 (마지막 Hello)
문자열 포함 여부 확인
text := "AutoHotkey v2 스크립트"
if InStr(text, "v2")
MsgBox("v2가 포함되어 있습니다!")
; 대소문자 무시하고 확인
if InStr(text, "autohotkey",, 0)
MsgBox("AutoHotkey가 포함되어 있습니다!")
🔄 문자열 치환
StrReplace - 문자열 바꾸기
text := "Hello World"
; StrReplace(문자열, 찾을것, 바꿀것, 대소문자구분, 출력:바꾼횟수, 최대치환수)
result := StrReplace(text, "World", "AHK")
MsgBox(result) ; "Hello AHK"
; 모든 공백 제거
text := "a b c d e"
result := StrReplace(text, " ", "")
MsgBox(result) ; "abcde"
; 바꾼 횟수 알아내기
text := "aaa bbb aaa"
result := StrReplace(text, "aaa", "xxx", , &count)
MsgBox("바꾼 횟수: " count) ; 2
실용 예제: 전화번호 포맷팅
phone := "01012345678"
; 하이픈 추가
formatted := SubStr(phone, 1, 3) "-" SubStr(phone, 4, 4) "-" SubStr(phone, 8)
MsgBox(formatted) ; "010-1234-5678"
✂️ 문자열 분리와 결합
StrSplit - 문자열 나누기
text := "사과,배,포도,딸기"
fruits := StrSplit(text, ",")
MsgBox(fruits[1]) ; "사과"
MsgBox(fruits[2]) ; "배"
; 모든 항목 출력
for fruit in fruits
MsgBox(fruit)
여러 구분자로 나누기
text := "하나;둘,셋|넷"
parts := StrSplit(text, [";", ",", "|"])
for part in parts
MsgBox(part) ; 하나, 둘, 셋, 넷
배열을 문자열로 합치기
fruits := ["사과", "배", "포도"]
; 직접 구현 (AHK v2에는 Join 내장 함수 없음)
JoinArray(arr, delimiter := ",") {
result := ""
for i, item in arr {
if (i > 1)
result .= delimiter
result .= item
}
return result
}
MsgBox(JoinArray(fruits, ", ")) ; "사과, 배, 포도"
🔠 대소문자 변환
StrUpper / StrLower
text := "Hello World"
upper := StrUpper(text) ; "HELLO WORLD"
lower := StrLower(text) ; "hello world"
MsgBox(upper)
MsgBox(lower)
StrTitle - 각 단어 첫 글자 대문자
text := "hello world"
title := StrTitle(text)
MsgBox(title) ; "Hello World"
🧹 공백 처리
Trim / LTrim / RTrim
text := " Hello World "
trimmed := Trim(text) ; "Hello World" (양쪽 공백 제거)
ltrimmed := LTrim(text) ; "Hello World " (왼쪽만)
rtrimmed := RTrim(text) ; " Hello World" (오른쪽만)
; 특정 문자 제거
text := "###Hello###"
result := Trim(text, "#") ; "Hello"
🎭 정규표현식 (RegEx) 기초
정규표현식은 패턴 매칭의 끝판왕입니다. 복잡해 보이지만 기초만 알면 매우 강력합니다!
RegExMatch - 패턴 찾기
text := "제 이메일은 test@example.com 입니다"
; 이메일 패턴 찾기
if RegExMatch(text, "\w+@\w+\.\w+", &match)
MsgBox("찾은 이메일: " match[]) ; "test@example.com"
기본 패턴 문법
| 패턴 | 의미 | 예제 |
|---|---|---|
\d |
숫자 하나 | \d\d\d → "123" |
\d+ |
숫자 하나 이상 | \d+ → "12345" |
\w |
문자/숫자/밑줄 | \w+ → "Hello_123" |
\s |
공백 문자 | \s+ → " " |
. |
아무 문자 하나 | a.c → "abc", "a1c" |
* |
0개 이상 | ab*c → "ac", "abc", "abbc" |
+ |
1개 이상 | ab+c → "abc", "abbc" |
? |
0개 또는 1개 | colou?r → "color", "colour" |
^ |
문자열 시작 | ^Hello |
$ |
문자열 끝 | World$ |
RegExReplace - 패턴으로 치환
; 모든 숫자 제거
text := "abc123def456"
result := RegExReplace(text, "\d+", "")
MsgBox(result) ; "abcdef"
; 전화번호 포맷팅
phone := "01012345678"
formatted := RegExReplace(phone, "(\d{3})(\d{4})(\d{4})", "$1-$2-$3")
MsgBox(formatted) ; "010-1234-5678"
; HTML 태그 제거
html := "<p>Hello <b>World</b></p>"
plain := RegExReplace(html, "<[^>]+>", "")
MsgBox(plain) ; "Hello World"
실용 예제: 이메일 유효성 검사
email := "user@example.com"
; 간단한 이메일 패턴
pattern := "^\w+@\w+\.\w+$"
if RegExMatch(email, pattern)
MsgBox("유효한 이메일입니다!")
else
MsgBox("잘못된 이메일 형식입니다!")
📋 클립보드와 문자열 처리
클립보드 텍스트 가공하기
; Ctrl+Shift+U: 선택한 텍스트를 대문자로
^+u::{
old := A_Clipboard
A_Clipboard := ""
Send("^c")
ClipWait(1)
A_Clipboard := StrUpper(A_Clipboard)
Send("^v")
Sleep(100)
A_Clipboard := old
}
; Ctrl+Shift+L: 선택한 텍스트를 소문자로
^+l::{
old := A_Clipboard
A_Clipboard := ""
Send("^c")
ClipWait(1)
A_Clipboard := StrLower(A_Clipboard)
Send("^v")
Sleep(100)
A_Clipboard := old
}
클립보드에서 특정 정보 추출
; Ctrl+Shift+E: 클립보드에서 이메일 추출
^+e::{
if RegExMatch(A_Clipboard, "\w+@[\w.]+", &match) {
MsgBox("찾은 이메일: " match[])
} else {
MsgBox("이메일을 찾을 수 없습니다")
}
}
🎮 실습 과제
과제 1: 문자열 뒤집기 함수
; "Hello" → "olleH"
과제 2: 단어 수 세기
; "Hello World Test" → 3
과제 3: 카멜케이스를 스네이크케이스로
; "helloWorld" → "hello_world"
정답 보기 👀
#Requires AutoHotkey v2.0
; 과제 1: 문자열 뒤집기
ReverseString(str) {
result := ""
Loop StrLen(str)
result := SubStr(str, A_Index, 1) . result
return result
}
MsgBox(ReverseString("Hello")) ; "olleH"
; 과제 2: 단어 수 세기
CountWords(str) {
str := Trim(str)
if (str = "")
return 0
words := StrSplit(str, " ")
return words.Length
}
MsgBox(CountWords("Hello World Test")) ; 3
; 과제 3: 카멜케이스 → 스네이크케이스
CamelToSnake(str) {
; 대문자 앞에 밑줄 추가하고 소문자로 변환
result := RegExReplace(str, "([A-Z])", "_$1")
result := StrLower(result)
result := LTrim(result, "_") ; 맨 앞 밑줄 제거
return result
}
MsgBox(CamelToSnake("helloWorld")) ; "hello_world"
MsgBox(CamelToSnake("getElementById")) ; "get_element_by_id"
📚 자주 쓰는 문자열 함수 정리
| 함수 | 설명 | 예제 |
|---|---|---|
StrLen(str) |
길이 | StrLen("abc") → 3 |
SubStr(str, start, len) |
부분 추출 | SubStr("Hello", 1, 2) → "He" |
InStr(hay, needle) |
위치 찾기 | InStr("Hello", "ll") → 3 |
StrReplace(str, old, new) |
치환 | StrReplace("ab", "b", "c") → "ac" |
StrSplit(str, delim) |
분리 | StrSplit("a,b", ",") → ["a","b"] |
StrUpper(str) |
대문자 | StrUpper("hi") → "HI" |
StrLower(str) |
소문자 | StrLower("HI") → "hi" |
Trim(str) |
공백 제거 | Trim(" hi ") → "hi" |
RegExMatch(str, pat) |
패턴 검색 | 이메일 찾기 등 |
RegExReplace(str, pat, rep) |
패턴 치환 | 태그 제거 등 |
🎯 다음 시간 예고
다음 글에서는 실전 예제 모음입니다:
- 자주 쓰는 스크립트 10선
- 바로 복사해서 쓸 수 있는 코드
- 업무 자동화 실전 팁
지금까지 배운 걸 총정리하는 시간! 💪
이전 글: [#12 파일 다루기]
다음 글: [#14 실전 예제 모음 - 바로 쓰는 스크립트 10선]
반응형
'🔬 과학·테크 > 🔥 AutoHotkey v2 입문 가이드' 카테고리의 다른 글
| AutoHotkey v2 입문 가이드 #15: 디버깅과 팁 - 문제 해결의 기술 (0) | 2025.12.18 |
|---|---|
| AutoHotkey v2 입문 가이드 #14: 실전 예제 모음 - 바로 쓰는 스크립트 10선 (0) | 2025.12.17 |
| AutoHotkey v2 입문 가이드 #12: 파일 다루기 - 읽고, 쓰고, 관리하기 (0) | 2025.12.15 |
| AutoHotkey v2 입문 가이드 #11: GUI 기초 - 나만의 창 만들기 (0) | 2025.12.14 |
| AutoHotkey v2 입문 가이드 #10: 키 리매핑 - 키보드 재창조하기 (0) | 2025.12.13 |