Skip to content

Instantly share code, notes, and snippets.

@LusainKim
Last active May 30, 2017 08:43
Show Gist options
  • Save LusainKim/43ca9a8884dff63f3c72701a1736f57d to your computer and use it in GitHub Desktop.
Save LusainKim/43ca9a8884dff63f3c72701a1736f57d to your computer and use it in GitHub Desktop.
문자열로 입력받은 IP 주소가 유효한지 정규식을 사용하여 검사하는 코드입니다.
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main()
{
regex rg { "^([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3})$" };
string input;
while (true)
{
getline(cin, input);
smatch m;
if (regex_search(input, m, rg))
{
int elem[4] { stoi(m[1]) , stoi(m[2]) , stoi(m[3]) , stoi(m[4]) };
for (auto p : elem)
{
if (!(0 <= p && p < 256))
goto nomatch;
}
cout << "match!" << endl;
}
else
{
nomatch:
cout << "no match..." << endl;
}
}
}
@sangheonhan
Copy link

제가 사용한 정규표현식은 조금 다른데 참고가 되었으면 합니다. PCRE 기준입니다.

/
    ^
        (BYTEDEC)\.
        (BYTEDEC)\.
        (BYTEDEC)\.
        (BYTEDEC)\.
    $
    (?(DEFINE)
        (?<BYTEDEC>25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)
    )
/x

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment