Qt5에서 제공하는 정규식 함수 globalMatch() 를 사용하여 문자열에 섞여 있는 ip주소를 추출하는 방법이 있습니다. IP 주소와 문자가 섞여있을 때 IP주소만 추출하는 방법을 알아보도록 하겠습니다.
1. IP 추출 예제 코드
#include <QRegularExpressionMatchIterator>
QString stringWithIP = "local 192.168.1.1 google 172.217.175.238 naver 23.130.200.104";
QRegularExpression re("(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)");
QRegularExpressionMatchIterator i = re.globalMatch(stringWithIP);
while ( i.hasNext() ){
QRegularExpressionMatch matches = i.next();
QString word_IP = matches.captured(0);
// Print >> word_IP
}
2. 코드 설명
사용한 예제 문자열에는 총 3개의 IP가 있습니다. "local 192.168.1.1 google 172.217.175.238 naver 23.130.200.104". 아래 IP 주소(IPv4) 정규식 패턴을 사용하여 일치하는 값이 있는지 확인합니다.
IPv4 정규식 패턴
^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$
QRegularExpression re("(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)");
패턴과 일치하는 문자열을 모두 검사합니다.
QRegularExpressionMatchIterator i = re.globalMatch(stringWithIP);
처음 i 는 결과 값을 가리키지 않고, 결과 값 바로 앞쪽을 가리키고 있습니다. 따라서 hasNext() 함수를 사용하여 값 존재 여부를 확인합니다. 값이 존재하면 next() 함수로 일단 결과 값을 받아옵니다. 그리고 captured() 함수로 패턴과 일치하는 문자열 값을 가져옵니다. captured(0)에서 0번 의미는, 전체 정규식 전체(entire) 패턴과 일치함을 의미합니다.
while (i.hasNext()){
QRegularExpressionMatch matches = i.next();
QString word_ip = matches.captured(0);
}
'Programming > C++' 카테고리의 다른 글
bash shell 스크립트 정규식 url 날짜 정보 추출 url 파일 다운 받기 (0) | 2022.11.19 |
---|---|
linux diff 명령어 no such file or directory 해결 방법 (0) | 2022.03.05 |
swp 파일 삭제해도 괜찮을까? 생성되는 이유(in Linux) (0) | 2021.10.31 |
fsync() 와 sync() 차이점 및 활용법(linux, Qt5) (0) | 2021.10.24 |
removeRecursively 한글 파일 삭제 실패 해결방법(Qt5) (0) | 2021.10.23 |
댓글