[c++] 문자열에서 URL 추출하는 방법

먼저, 정규 표현식을 위해 <regex> 헤더 파일을 include 합니다. 그런 다음, std::regex를 사용하여 URL 패턴을 정의합니다.

다음은 C++에서 문자열에서 URL을 추출하는 간단한 예제입니다:

#include <iostream>
#include <string>
#include <regex>

int main() {
    std::string input = "This is a sample text with a URL http://www.example.com/path";
    std::regex url_regex("(https?|ftp)\\:\\/\\/[^\\s/$.?#].[^\\s]*");
    std::smatch url_match;

    if (std::regex_search(input, url_match, url_regex)) {
        std::cout << "Found URL: " << url_match[0] << std::endl;
    } else {
        std::cout << "URL not found" << std::endl;
    }

    return 0;
}

이 코드에서, 정규 표현식 (https?|ftp)\:\/\/[^\\s/$.?#].[^\\s]*은 일반적인 URL 형식에 대한 패턴을 정의합니다. regex_search 함수를 사용하여 입력 문자열에서 URL에 일치하는지 확인하고, 그 결과를 출력합니다.

더 복잡한 URL을 처리하는 경우에는 더 정교한 정규 표현식이 필요할 수 있습니다. 또는 URL의 여러 부분을 따로 추출해야 하는 경우도 있을 수 있습니다. 그런 경우에는 더 많은 정규 표현식 패턴이나 문자열 처리 로직이 필요할 것입니다.

더 많은 정보를 원하신다면, 아래의 레퍼런스를 참고하시기 바랍니다: