c++ - Tricky substring problems -
i'm having problem substrings, have string in format below i'm using getline.
richard[12345/678910111213141516] murdered
what have been using find_last_of
, find_first_of
positions in between brackets , forward slashes retrieve each field. have working , functional have ran problem. name field can 32 characters in length, , can contain / , [] when ran user url name did not that. numbers random on per user basis. i'm retrieving each field string, name , 2 identifying numbers.
another string can this, grabbing 6 total substrings.
richard[12345/678910111213141516] murdered ralph[54321/161514131211109876]
which just huge mess, thinking doing starting , moving front, if second name field (ralph) contains / or [] going ruin count retrieving first part. insight helpful. thank you.
in nutshell. how account these.
names can contain alpha / numerical , special character.
richard///[][][12345/678910111213141516] murdered ralph[/[54321/161514131211109876]
the end result 6 substrings containing this.
- richard///[][]
- 12345
- 678910111213141516
- ralph[/
- 54321
- 161514131211109876
regex has been mentioned me, don't know if better suited task or not, included tag more experienced might answer/comment.
here regex way obtain values:
string str = "richard///[][][12345/678910111213141516] murdered ralph[/[54321/161514131211109876]"; regex rgx1(r"(([a-z]\w*\s*\s*)\[(\d+)?(?:\/(\d+))?\])"); smatch smtch; while (regex_search(str, smtch, rgx1)) { std::cout << "name: " << smtch[1] << std::endl; std::cout << "id1: " << smtch[2] << std::endl; std::cout << "id2: " << smtch[3] << std::endl; str = smtch.suffix().str(); }
see ideone demo
the regex (\s*)\[(\d+)?(?:/(\d+))?\]
matches:
(\s*)
- (group 1) 0 or more non-whitespace symbols, as many possible.\[
- opening square bracket (must escaped special character in regex reserved character classes)(\d+)?
- (group 2) 1 or more digits (optional group, can empty)(?:/(\d+))?
- non-capturing optional group matching/
- literal/
(\d+)
- (group 3) 1 or more digits.
\]
- closing square bracket.
Comments
Post a Comment