Regular expressions C++

Asked

Viewed 473 times

2

I have a text with the following formatting

Concept:personasia:toby_pizur:personasia:test

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

2 answers

5

What you want to get from string is very easy to obtain without regular expressions, as @rLinhares has already shown.

If you wanted to do it with regular expressions, which I don’t recommend, you could do it with:

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

See this regex in 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 c++ would capture so:

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

See this code in Ideone

  • Deleted answer ok. obg: https://answall.com/q/288920/8063

  • @dvd I think you made the most correct, face the way the site works :)

4


Test that 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 take the "last index" of : and take the substring after him.

  • 2

    Thank you very much!! the correct function is the find_last_of, but helped me a lot by giving me a north.

  • Massa, @Lucasvieira ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.