Regular Expressions C ++

2

I have text with the following formatting

  

concept: personasia: toby_pizur: personasia: test

How do I get a string with this formatting, only the text after the last colon (:)? In the example above, I would only have "test".

    
asked by anonymous 04.04.2018 / 21:06

2 answers

4

Test this code:

string palavraRetorno = "";
string palavra = "concept:personasia:toby_pizur:personasia:teste";
int indice = palavra.LastIndexOf(':');
if (indice >= 0)
    palavraRetorno = palavra.substr(índice + 1);

The idea is to get the "last index" of : and get the substring after it.

    
04.04.2018 / 21:12
5

What you want to get from string is quite easy to get without regular expressions, as @rLinhares already showed.

If however I wanted to do with regular expressions, which I do not recommend, I could do it with:

:((?!.*:).*$)

View this regex on regex101

Explanation:

:    - dois pontos
(    - o que vem a seguir é o que vai ser capturado no primeiro grupo
(?!  - que não tenha a seguir
.*:) - qualquer coisa e dois pontos
.*$) - continua o grupo de captura apanhando tudo até ao fim da linha

In the code in c ++ it would capture like this:

std::regex rgx(":((?!.*:).*$)");
std::smatch match;
std::string input = "concept:personasia:toby_pizur:personasia:teste";

if (std::regex_search(input, match, rgx))
{
    std::cout << match[1];
}

View this code on Ideone

    
04.04.2018 / 23:45