Replace a specific part of a string that includes a variable in objective C -
i've been spending hours trying figure out no luck. have string, call filecontent, holds content of file utf-8 encoding need modify.
this filecontent has specific section variable need find, replace , overwrite original file with. know how replace section once found , overwrite original file, struggle find section has variable itself.
the variable made of random numbers , letters random length uniquely identify individual user's session.
this how variable appears in section of file read filecontent:
+option1 (variable) +option2
the surrounding text (+option1 , +option2) , whitespaces constant, making easy locate manually. section part of longer line must left intact.
i've tried nsregularexpression:regularexpressionwithpattern: variety of wildcards, using \ escape "+", returns:
the value “+option1 ... +option2” invalid.
i tried wildcards documentation , various combinations of them found in other answered questions eg.
".*\+option1 (.*) \+option2.*".
is nsregularexpression not appropriate task? should using nsrange or nsscanner instead, perhaps different?
as john elemans mentioned, if +option1 , +option2 fixed , unique, can use rangeofstring this. first, need find index of both:
// filecontent holds ".... +option1 yourstring +option2 ...." int idx1 = [filecontent rangeofstring:@"+option1"].location; int idx2 = [filecontent rangeofstring:@"+option2"].location; int len2 = [@"+option2" length]; if ((idx1>=0)&&(idx2>=0)) { nsstring *str= [filecontent substringwithrange:nsmakerange(idx1, idx2+len2-idx1)]; // str holds "+option1 yourstring +option2" // split array nsarray *arr = [str componentsseparatedbystring:@" "]; // array arr has [+option1,yourstring,+option2] // can string arr[1]; nslog(@"mystring %@",arr[1]); }
do note if option1 , 2 name changed or order changed in anyway, break. note have not tested code. might break @ nsmakerange area... check index/length properly.
Comments
Post a Comment