본문 바로가기
Programming/C++

정규식 IP주소만 추출하는 방법 in Qt5

by AUTORI 2021. 11. 6.

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);
}

 

댓글