Monday 15 September 2014

c++ - Checking a string for matching substrings -



c++ - Checking a string for matching substrings -

i have long sequence of segments separated delimiter '-'. of form:

i-am-logged-into-stackoverflow-i-am-using-stackoverflow- i-am-reading-a-book-a-i-have-written-a-book-b-

the user specifies segments have compare.

say, string - 1, above: inputs 5 , 9. both contain stackoverflow, homecoming true.

for string - 2, segments 6, 12. but. different books a,b. so, homecoming false.

i have tried using std::regex.

for indices not entered user, fill in portions of temporary string with ([^-]+)-, i.e. string of 1 or more characters not containing -, ending that.

for 2 indices user inputs,i face problem. if go capturing groups , specify ([^-]+-) in first index , utilize \1 (or nth capturing group) sec index, results inconsistent. book matches anewbook not expected. in cases, a- matches not-.

then match sentences above, temp string.

how check equality - characters start end, , length of substrings @ given indices?

also, find question similar, of results there not consistent. constructing regular expression

ps: considering fact easy regex rather extracting segments @ given indices of string , comparing same, prefer former. number of string may run hundreds.

better solutions appreciated.

a possible solution (surely not one) utilize std::find , extract 2 substrings comparison

(warning: next code hasn't been extensively tested , might contain errors, intended concept thought farther refinement suit needs)

bool match_positions(const std::string& str, int p1, int p2) { int wordno = 1; size_t beg = 0, pos; std::string first, second; while ((pos = str.find('-', beg)) != std::string::npos || (first.empty() && second.empty()) ) { if (wordno == p1) first = str.substr(beg, pos - beg); if (wordno == p2) sec = str.substr(beg, pos - beg); beg = pos + 1; ++wordno; } if (first.empty() || second.empty()) homecoming false; else if (!first.compare(second)) homecoming true; else homecoming false; }

example

since (as understood it) "find-the-substring-at-nth-delimiter" problem, wouldn't go regex , leave more complex pattern matching tasks.

c++ regex substring

No comments:

Post a Comment