Delete occurances at the end of a string - iOS - ios

Say you have a NSString *testString = #"Abcd!!!!";, note the four exclamation marks, how can I delete all exclamation marks as efficiently as possible?
The exclamation marks can be any number of amount, and can only be deleted if they're in consecutive trailing order.
One example might be:
NSString *testString = #"ABC!D!!!!!";
The result would then be:
NSString *result = #"ABC!D";

Since you don't know how many ! you'll be removing from the string, you could do it with a regular expression.
NSString *string = #"ABC!D!!!!!";
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);
Regex aren't always the most efficient way to solve these sorts of problems, but in this case, I don't think there would be a measurable gain doing it another way.

Related

SubString from existing string iOS

I have two strings as followed:
NSString *newStr = #"143.2a";
NSString *expression = #"^([0-9]*)(\\.([0-9]{0,10})?)?$";
I want to substring "newStr" such as all my characters in "expression" should be present after subString. Like
NSString * extractedString = #"143.2";
(except all alphabets and symbols other than single'.')
How shall I do this?
First of all, your regex pattern won't extract that string.
If you want to check for one or more digits followed be a dot followed be one or more digits the pattern is supposed to be
NSString *expression = #"\\d+\\.\\d+";
To extract the string use the NSRegularExpression class as suggested by Larme.
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression options:0 error:nil];
NSTextCheckingResult *firstMatch = [regex firstMatchInString:newStr options:0 range:NSMakeRange(0, newStr.length)];
if (firstMatch) {
NSString *extractedString = [newStr substringWithRange:firstMatch.range];
NSLog(#"%#", extractedString);
} else {
NSLog(#"Not Found");
}

How do I extract a specific part of a string with NSRegularExpression?

Say I have a bunch of different strings:
"http://website.com/283/comments/einp43/2398/32/34/23/4/4"
"http://website.com/23283/l34/comments/inhd3/3928/3/2/3"
"http://website.com/pics/283/comments/en43/a89st/389238/a823/"
"http://website.com/pics/hd/283/comments/as87/asd7j/3"
And I always want the portion that follows comments/ which is a valuable ID. But I don't want the comments part, I just want the ID.
How do I isolate/extract that?
Assuming the website name is stored as an NSString called websiteName:
NSArray *components = [websiteName componentsSeparatedByString:#"comments/"];
NSString *valuableID = [components lastObject];
(Edit: I didn't notice the mention of NSRegularExpression in the title until after posting this answer, but I don't think regex is necessary in this case since you're looking for a single constant string and have no need for complex pattern recognition.)
You can do it with regex, try this code
NSString *string = #"http://website.com/23283/l34/comments/inhd3/3928/3/2/3";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"/comments/([^/]*)" options:NSRegularExpressionCaseInsensitive error:nil];
[regex enumerateMatchesInString:string options:0 range:NSMakeRange(0, string.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSString *subStr = [string substringWithRange:[result rangeAtIndex:1]];
NSLog(#"commentId = %#", subStr);
}];
output:
commentId = inhd3

how to replace many occurrences of comma by single comma

Earlier I had string as 1,2,3,,5,6,7
To replace string, I used stringByReplacingOccurrencesOfString:#",," withString:#",", which gives output as 1,2,3,5,6,7
Now I have string as below.
1,2,3,,,6,7
To replace string, I used stringByReplacingOccurrencesOfString:#",," withString:#",", which gives output as 1,2,3,,6,7
Is there way where I can replace all double comma by single comma.
I know I can do it using for loop or while loop, but I want to check is there any other way?
for (int j=1;j<=100;j++) {
stringByReplacingOccurrencesOfString:#",," withString:#","]]
}
NSString *string = #"1,2,3,,,6,7";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#",{2,}" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:#","];
NSLog(#"%#", modifiedString);
This will match any number of , present in the string. It's future proof :)
Not the perfect solution, but what about this
NSString *string = #"1,2,3,,,6,7";
NSMutableArray *array =[[string componentsSeparatedByString:#","] mutableCopy];
[array removeObject:#""];
NSLog(#"%#",[array componentsJoinedByString:#","]);

stringByReplacingOccurrencesOfString function

I am new to ios development.
NSString *newString2 = [aString stringByReplacingOccurrencesOfString:#"1," withString:#""];
My problem is i do not know how to check for any number i.e. stringByReplacingOccurrencesOfString:#"anyInt," where any Int is any integer number from 1 to N.
Thanks in advance!
Using regular expressions is the best solution:
NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"[1-9]" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:#""];
Check official NSRegularExpression documentation, there is also a good tutorial here
A regular expression is probably the easiest solution. Whether you want to remove just single digits or multiple digits, a regular expression can help.
NSString *aString = #"Apple 10, Banana 3, Carrot 5, Durian 42, Eggplant 4,";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"[0-9]+," options:0 error:NULL];
NSString *newString = [regex stringByReplacingMatchesInString:aString options:0 range:NSMakeRange(0, [aString length]) withTemplate:#""];
NSLog(#"%#", newString);
// result should be "Apple Banana Carrot Durian Eggplant "
Regular expressions may seem overwhelming or difficult to understand at first, but it is only because they can be very powerful for searching and replacing text. Have a look at the overview section of the NSRegularExpression documentation for more information.
For nos in first part greater than 0, second part is shown. For 0 in first part, -- is shown.
Try the below code,
NSString * aString = #"1,10";
NSString *newString2;
NSArray *items = [aString componentsSeparatedByString:#","];
if([[items objectAtIndex:0] integerValue]>0)
newString2 = [items objectAtIndex:1];
else
newString2 = #"--";
Just these two lines to remove all numbers from a string.
NSCharacterSet *numbers = [NSCharacterSet
characterSetWithCharactersInString:#"0123456789"];
NSString *newString = [[tempstr componentsSeparatedByCharactersInSet: numbers] componentsJoinedByString:#""];
If you want to check the range and then you want to replace then use below api:-
- (NSString *)stringByReplacingCharactersInRange:(NSRange)range withString:(NSString *)replacement
why you want to check the existence of the Integer because ultimate you'll replace it with ''. So just use the below line
NSString *newString2 = [aString stringByReplacingOccurrencesOfString:[NSString StringWithFormat:#"%d", anyInt], withString:#""];
Above line will fulfill your requirement.

NSMutableString replaceOccurrencesOfString replacing whole words

Is there a way to use replaceOccurrencesOfString (from NSMutableString) to replace whole words?
For example, if I want to replace all occurrences of a fraction in a string, like "1/2", I'd like that to match only that specific fraction. So if I had "11/2", I would not want that to match my "1/2" rule.
I've been trying to look for answers to this already, but I am having no luck.
You could use word boundaries \b with Regex. This example matches the "1/2" at the start and the end of the example string, but neither of the middle options
// Create your expression
NSString *string = #"1/2 of the 11/2 objects were 1/2ed in (1/2)";
NSError *error = nil;
NSRegularExpression *regex =
[NSRegularExpression
regularExpressionWithPattern:#"\\b1/2\\b"
options:NSRegularExpressionCaseInsensitive
error:&error];
// Replace the matches
NSString *modifiedString =
[regex stringByReplacingMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
withTemplate:#"HALF USED TO BE HERE"];

Resources