Romz
Romz

Reputation: 1457

Efficient way to get all substrings from a string that contains special characters

I have got a string like this:

    std::string input = "This* #is # #just# a *random ##string #*that# 
may contain any# char*cters#";

I need to get all substrings that:

1) Between character '#'

AND

2) Contain character '*'

The result will be:

" a *random "
"*that"
" char*cters"

I do it like this:

std::vector<std::string> substrings;
boost::split(substrings, input, boost::is_any_of("#"));
for (int i = 0; i < substrings.size(); i++)
{
if (i != 0 // first and last substring is not between '#' (only from one side)
   && (i != substrings.size() - 1) 
   && !substrings[i].empty() 
   && substrings[i].find('*') != std::string::npos) // if contain '*' character
   {
      // Here I've got my result
   }
}

It works, but is there any efficient solutions to do this ?

Upvotes: 1

Views: 917

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

You can use a regular expression "#([^#*]*[*][^#]*)#" to extract all such strings.

The expression describes the kind of substrings that you are looking for:

  • Start in a #
  • Has zero or more characters other than an asterisk,...
  • which is followed by at least one asterisk
  • which is followed by zero or more characters other than #
  • which is followed by # at the end.

Upvotes: 1

Related Questions