remove string between parentheses [iOS] - ios

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!

Related

iOS - NSString regex match

I have a string for example:
NSString *str = #"Strängnäs"
Then I use a method for replace scandinavian letters with *, so it would be:
NSString *strReplaced = #"Str*ngn*s"
I need a function to match str with strReplaced. In other words, the * should be treated as any character ( * should match with any character).
How can I achieve this?
Strängnäs should be equal to Str*ngn*s
EDIT:
Maybe I wasn't clear enough. I want * to be treated as any character. So when doing [#"Strängnäs" isEqualToString:#"Str*ngn*s"] it should return YES
I think the following regex pattern will match all non-ASCII text considering that Scandinavian letters are not ASCII:
[^ -~]
Treat each line separately to avoid matching the newline character and replace the matches with *.
Demo: https://regex101.com/r/dI6zN5/1
Edit:
Here's an optimized pattern based on the above one:
[^\000-~]
Demo: https://regex101.com/r/lO0bE9/1
Edit 1: As per your comment, you need a UDF (User defined function) that:
takes in the Scandinavian string
converts all of its Scandinavian letters to *
takes in the string with the asterisks
compares the two strings
return True if the two strings match, else false.
You can then use the UDF like CompareString(ScanStr,AsteriskStr).
I have created a code example using the regex posted by JLILI Amen
Code
NSString *string = #"Strängnäs";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"[^ -~]" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:#"*"];
NSLog(#"%#", modifiedString);
Output
Str*ngn*s
Not sure exactly what you are after, but maybe this will help.
The regular expression pattern which matches anything is. (dot), so you can create a pattern from your strReplaced by replacing the *'s with .'s:
NSString *pattern = [strReplaced stringByReplacingOccurencesOfString:#"*" withString:"."];
Now using NSRegularExpression you can construct a regular expression from pattern and then see if str matches it - see the documentation for the required methods.

How can i trim a blank(empty) line in NSString?

I have textView where user can add text in new line. but when user enter multiple new line and not enter a any text then i want skip all that line and just use only one new line.
I have String like below.
Hello,
How r u?
I want a string like this
Hello
How r u?
I have tried this but not working
strContects=[strContects stringByReplacingOccurrencesOfString:#"\n\n" withString:#"\n"];
How can i do this?
Hope u will understand?
You can replace multiple occurrence of omit multiple newline characters with single one by following regular expressions code
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\n+" options:0 error:NULL];
NSString *newString = [regex stringByReplacingMatchesInString:myString options:0 range:NSMakeRange(0, [myString length]) withTemplate:#"\n"];
this will print
Hello,
How r u? //in new line(all \n omitted with single \n)
If the goal here is removing all blank lines - not just consolidating multiple newlines - then it is worth noting the accepted answer wont remove an initial blank line in the string; eg "\nHello..."
A bit more involved, but try this category:
- (NSString*)stringByRemovingBlankLines
{
NSScanner *scan = [NSScanner scannerWithString:self];
NSMutableString *string = NSMutableString.new;
while (!scan.isAtEnd) {
[scan scanCharactersFromSet:NSCharacterSet.newlineCharacterSet intoString:NULL];
NSString *line = nil;
[scan scanUpToCharactersFromSet:NSCharacterSet.newlineCharacterSet intoString:&line];
if (line) [string appendFormat:#"%#\n",line];
}
if (string.length) [string deleteCharactersInRange:(NSRange){string.length-1,1}]; // drop last '\n'
return string;
}
(BTW - this can also handle other types of 'newline' characters which the accepted answer does not. This wasn't asked for, but it came up in the comments)

How can I search for and remove an escaped character from an NSString?

I am reading a line of code in from a source file on disk and the line is a string, and it is of a string that contains HTML code in it:
line = #"format = #"<td width=\"%#\">";"
I need to remove the escaped characters from the html string. So any place that there is a '\"', I need to replace it with ''. I tried this:
[line stringByReplacingOccurrencesOfString:#"\\""" withString:#""];
But it only removed the '\' character, not the accompanying '"'. How can I remove the escaped '"' from this string?
EDIT: The key part of this problem is that I need to figure out a way to identify the location of the first #", and the closing " of the string declaration, and ignore/remove everything else. If there is a better way to accomplish this I am all ears.
[s stringByReplacingOccurrencesOfString:#"\\\"" withString:#""]
The replacement string there is a slash, which has to be escaped in the literal replacement string using another slash, followed by a quote, which also has to be escaped in the literal by a slash.
Try use this:
NSString *unfilteredString = #"!##$%^&*()_+|abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
NSCharacterSet *notAllowedChars = [[NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"] invertedSet];
NSString *resultString = [[unfilteredString componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:#""];
NSLog (#"Result: %#", resultString);

Extract text from a NSString using regular expressions

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);

Removing new line characters from NSString

I have a NSString like this:
Hello
World
of
Twitter
Lets See this
>
I want to transform it to:
Hello World of Twitter Lets See this >
How can I do this? I'm using Objective-C on an iPhone.
Split the string into components and join them by space:
NSString *newString = [[myString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:#" "];
Splitting the string into components and rejoining them is a very long-winded way to do this. I too use the same method Paul mentioned. You can replace any string occurrences. Further to what Paul said you can replace new line characters with spaces like this:
myString = [myString stringByReplacingOccurrencesOfString:#"\n" withString:#" "];
I'm using
[...]
myString = [myString stringByReplacingOccurrencesOfString:#"\n\n" withString:#"\n"];
[...]
/Paul
My case also contains \r, including \n, [NSCharacterSet newlineCharacterSet] does not work, instead, by using
htmlContent = [htmlContent stringByReplacingOccurrencesOfString:#"[\r\n]"
withString:#""
options:NSRegularExpressionSearch
range:NSMakeRange(0, htmlContent.length)];
solved my problem.
Btw, \\s will remove all white spaces, which is not expected.
Providing a Swift 3.0 version of #hallski 's answer here:
self.content = self.content.components(separatedBy: CharacterSet.newlines).joined(separator: " ")
Providing a Swift 3.0 version of #Kjuly 's answer here (Note it replaces any number of new lines with just one \n. I would prefer to not use regular express if someone can point me a better way):
self.content = self.content.replacingOccurrences(of: "[\r\\n]+", with: "\n", options: .regularExpression, range: Range(uncheckedBounds: (lower: self.content.startIndex, upper: self.content.endIndex)));

Resources