I have a NSString in this format:
"Key1-Value1,Key2-Value2,Key3-Value3,..."
I need only keys (with a space after every comma):
Key1, Key2, Key3, etc.
I thought to create an array of components from the string using the comma as separator, and after, for every component, extract all characters since the "-"; then I'd serialize the array elements. But I fear this could be very heavy about performances.
Do you know a way to do this using regular expressions?
The regex will greatly depend on the data you are using. For example if the key or value is allowed to be all numbers, or allowed to contain space and punctuation, you would need to modify the regex. For your current example however this will work.
NSString *example = #"Key1-Value1,Key2-Value2,Key3-Value3,...";
NSString *result = [example stringByReplacingOccurrencesOfString:#"(\\w+)-(\\w+),?"
withString:#"$1, "
options:NSRegularExpressionSearch
range:NSMakeRange(0, [example length])];
result = [result stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#", "]];
NSLog(#"%#", result);
Related
i have a NSString with parentheses in it.
I would like to remove the Text inside of the parentheses.
How to do that? ( In Objective-C )
Example String:
Tach auch. (lockeres Ruhrdeutsch) Und Hallo!
I would like to Remove "(lockeres Ruhrdeutsch)" from the String,
but the Strings i have to edit are always different.
How can i remove the String betweeen "(" and ")"?
Best Regards
Use regular expression:
NSString *string = #"Tach auch. (lockeres Ruhrdeutsch) Und Hallo!";
NSString *filteredString = [string stringByReplacingOccurrencesOfString:#"\\(.*\\)"
withString:#""
options:NSRegularExpressionSearch range:NSMakeRange(0, string.length)];
NSLog(#"%#", filteredString);
If you want to consider also a whitespace character after the closing parenthesis, add \\s? to the end of the regex pattern.
Here is the function you can call to get your required string:
-(NSString*)getStringWithBlankParaFrom:(NSString*)oldStr{
NSArray*strArray1=[oldStr componentsSeparatedByString:#"("];
NSString*str2=[strArray1 objectAtIndex:1];
NSArray*strArray2 =[str2 componentsSeparatedByString:#")"];
NSString*strToReplace=[strArray2 objectAtIndex:0];
return [oldStr stringByReplacingOccurrencesOfString:strToReplace withString:#""];
}
This function is valid for the string which contains one pair of parentheses**()**
You can change it as per your requirement.
Hope this helps!
For an app I'm working on, I need to check if a text field contains only the letters A, T, C, or G. Furthermore, I would like to make specialized error messages for any other inputed characters. ex) "Don't put in spaces." or "The letter b isn't an accepted value." I have read a couple other posts like this, but they are alphanumeric, I only want specified characters.
One approach for you, far from unique:
NString has methods to find substrings, represented as an NSRange of location & offset, made up from characters in a given NSCharacterSet.
The set of what should be in the string:
NSCharacterSet *ATCG = [NSCharacterSet characterSetWithCharactersInString:#"ATCG"];
And the set of what shouldn't:
NSCharacterSet *invalidChars = [ATCG invertedSet];
You can now search for any range of characters consisting of invalidChars:
NSString *target; // the string you wish to check
NSRange searchRange = NSMakeRange(0, target.length); // search the whole string
NSRange foundRange = [target rangeOfCharacterFromSet:invalidChars
options:0 // look in docs for other possible values
range:searchRange];
If there are no invalid characters then foundRange.location will be equal to NSNotFound, otherwise you change examine the range of characters in foundRange and produce your specialised error messages.
You repeat the process, updating searchRange based on foundRange, to find all the runs of invalid characters.
You could accumulate the found invalid characters into a set (maybe NSMutableSet) and produce the error messages at the end.
You can also use regular expressions, see NSRegularExpressions.
Etc. HTH
Addendum
There is a really simple way to address this, but I did not give it as the letters you give suggest to me you may be dealing with very long strings and using provided methods as above may be a worthwhile win. However on second thoughts after your comment maybe I should include it:
NSString *target; // the string you wish to check
NSUInteger length = target.length; // number of characters
BOOL foundInvalidCharacter = NO; // set in the loop if there is an invalid char
for(NSUInteger ix = 0; ix < length; ix++)
{
unichar nextChar = [target characterAtIndex:ix]; // get the next character
switch (nextChar)
{
case 'A':
case 'C':
case 'G':
case 'T':
// character is valid - skip
break;
default:
// character is invalid
// produce error message, the character 'nextChar' at index 'ix' is invalid
// record you've found an error
foundInvalidCharacter = YES;
}
}
// test foundInvalidCharacter and proceed based on it
HTH
Use NSRegulareExpression like this.
NSString *str = #"your input string";
NSRegularExpression *regEx = [NSRegularExpression regularExpressionWithPattern:#"A|T|C|G" options:0 error:nil];
NSArray *matches = [regEx matchesInString:str options:0 range:NSMakeRange(0, str.length)];
for (NSTextCheckingResult *result in matches) {
NSLog(#"%#", [str substringWithRange:result.range]);
}
Also for the options parameter you have to look in the documentation to pick one that fits.
Look at the NSRegularExpression class reference.
Visit: https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html
After extracting a string from JSON response:
NSString *responseMessage = [NSString stringWithFormat:#"%#",[[JSON objectForKey:#"Response"]valueForKey:#"Message"]];
NSLog(#"<%#>",responseMessage);
It looks like this:
<(
"not found"
)>
This is the relevant code:
So when I try to compare it, isEqualToString returns always false
([responseMessage isEqualToString:#"not found"])?NSLog(#"They are equal"):NSLog(#"They are different");//they are different
How to get rid of these parentheses to better compare the two strings? Thanx in advance.
It looks like you have an array here (which in Objective-C will print as a list with parentheses).
What is the source JSON string?
If it is an array, you want to iterate over its elements, or maybe just pull out the first one.
You could try using the NSRegularExpression to remove if any brackets existing in your code. You can find different combinations for regular expressions to use.
NSString *expression = #"\\s+\\([^()]*\\)";
while ([responseMessage rangeOfString:expression options:NSRegularExpressionSearch|NSCaseInsensitiveSearch].location!=NSNotFound)
{
responseMessage = [responseMessage stringByReplacingOccurrencesOfString:expression withString:#"" options:NSRegularExpressionSearch|NSCaseInsensitiveSearch range:NSMakeRange(0, [responseMessage length])];
}
NSLog(#"returnResponse %#",responseMessage);
I have the following NSString:
productID = #"com.sortitapps.themes.pink.book";
At the end, "book" can be anything.... "music", "movies", "games", etc.
I need to find the third period after the word pink so I can replace that last "book" word with something else. How do I do this with NSRange? Basically I need this:
partialID = #"com.sortitapps.themes.pink.";
You can try a backward search for the dot and use the result to get the desired range:
NSString *str = #"com.sortitapps.themes.pink.book";
NSUInteger dot = [str rangeOfString:#"." options:NSBackwardsSearch].location;
NSString *newStr =
[str stringByReplacingCharactersInRange:NSMakeRange(dot+1, [str length]-dot-1)
withString:#"something_else"];
You can use -[NSString componentsSeparatedByString:#"."] to split into components, create a new array with your desired values, then use [NSArray componentsJoinedByString:#"."] to join your modified array into a string again.
Well, although this isn't a generic solution for finding characters, in your particular case you can "cheat" and save code by doing this:
[productID stringByDeletingPathExtension];
Essentially, I'm treating the name as a filename and removing the last (and only the last) extension using the NSString method for this purpose.
I am making an app where there is a requirement to store ASCII art into a database. I store the strings in the below format.
"___________\n |---------|-O\n/___________\\n|______________|\n\____________/"
When I retrieve the data and display it in a label, I want the newline characters and backslashes to be parsed so as to display the real shape of the ASCII art.
How should I parse this kind of strings?
NSString has a method to do what you want, which is to replace a litteral \n, with a newline character (which is symbolized as \n). In a c-format string you can use a double slash to let the library know the second slach is a real one and not an escape symbol. So this should work assuming you have been able to load your data from sqlite into an NSString:
newString = [yourStringFromSQLite stringByReplacingOccurrencesOfString:#"\\n" withString:#"\n"];
If you are using \n just for creating new lines then instead of that just keep space while inserting value in database and set following properties for label ->
1)keep width just to fit first word.
2)linebreakmode to wordwrap (so as width will not be available it will wrap next word to new line)
3)set no. of lines to 0
Hope this will help.
try to use the scanner for remove the html entities
- (NSString *)flattenHTML:(NSString *)html trimWhiteSpace:(BOOL)trim {
NSScanner *theScanner;
NSString *text = nil;
theScanner = [NSScanner scannerWithString:html];
while ([theScanner isAtEnd] == NO) {
[theScanner scanUpToString:#"<" intoString:NULL] ;
[theScanner scanUpToString:#">" intoString:&text] ;
html = [html stringByReplacingOccurrencesOfString:[ NSString stringWithFormat:#"%#>", text] withString:#" "];
}
return trim ? [html stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] : html;
}
and call this method where your trimmed string need to display