2017-01-30 1 views
-3

C++ 11에서 정규 표현식과 일치하는 문자열의 첫 번째 부분을 반환하는 간단한 방법은 무엇입니까?현대 C++가있는 문자열에서 첫 번째 정규식 일치를 반환하는 간단한 방법은 무엇입니까?

예 : 문자열 "The great brown fox jumped over the lazy dog."와 정규 표현식 /g[a-z]+/를 들어 반환 일치 "great"

+0

네, 정규식이다가 사용할 데, 당신은 다음처럼 작성할 수 있습니다. 너 뭐하려고? – Qix

+0

[도움말 페이지] (http://stackoverflow.com/help), 특히 [여기에 대해 내가 들려 줄 주제는 무엇입니까?] (http://stackoverflow.com/help) 섹션을 읽어보십시오./on-topic) 및 [ "어떤 유형의 질문을하지 않아야합니까?"] (http://stackoverflow.com/help/dont-ask). 또한 [둘러보기] (http://stackoverflow.com/tour)와 [좋은 질문을하는 방법에 대해 읽어보십시오.] (http://stackoverflow.com/help/how-to-ask). 마지막으로 [Minimal, Complete, Verifiable Example] (http://stackoverflow.com/help/mcve)를 만드는 방법을 배우십시오. –

+0

@Someprogrammerdude : OP가 무엇을 요구하는지 알았습니다. 솔직히 말해서, 그것은 아마도 잘 속는 사람일지도 모른다. – einpoklum

답변

0

이 당신이 무엇을 의미하는지는 것입니까? 당신이 함수로 그것을 원하는 경우

#include <regex> 
#include <iostream> 

// ... include first_match() somewhere... 

int main() 
{ 
    std::string subject("The great brown fox jumped over the lazy dog."); 
    std::string result; 
    std::regex re("g[a-z]+"); 
    std::smatch match; 
    if (std::regex_search(subject, match, re)) { std::cout << match.str(0); } 
    else { std::cout << "(No matches)"; } 
    std::cout << '\n'; 
    return 0; 
} 

, 나 자신 std::optional를 사용할 수 있도록 것입니다. 이것은 C++ 17의 일부이며 C++ 11에는 포함되어 있지 않지만 C++ 14에서는 std::experimental::optional으로, C++ 11에서는 Boost의 boost::optional을 대신 사용할 수 있습니다.

std::optional<std::string> first_match(
    const std::string& str, 
    const std::regex& expression) 
{ 
    std::smatch match; 
    return std::regex_search(str, match, expression) ? 
     std::optional<std::string>(match.str(0)) : std::nullopt; 
} 

다음과 같이 사용할 수 있습니다 :

#include <regex> 
#include <iostream> 
#include <optional> 

int main() 
{ 
    std::cout << 
     first_match(
      "The great brown fox jumped over the lazy dog.", "g[a-z]+" 
     ).value_or("(no matches)") << '\n'; 
    return 0; 
} 
관련 문제