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:#","]);
Related
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");
}
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.
I am trying to write a function that has an NSString and parses it returning an array of tags.
The definition of a tag is any nsstring text that starts with # and contains only alphanumeric characters after the #.
Is this correct?
#.*?[A-Za-z0-9]
I want to use matchesInString:options:range: but need some help.
My function is:
- (void) getTags
{
NSString* str = #"This is my string and a couple of #tags for #you.";
// Range is 0 to 48 (full length of string)
// NSArray should contain #tags and #you only.
Thanks!
The patten "#.*?[A-Za-z0-9]" matches a # which is followed by zero or more
characters which are not in the set [A-Za-z0-9]. What you probably want is
NSString *pattern = #"#[A-Za-z0-9]+";
The you can create a regular expression using that pattern:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
and enumerate all matches in the string:
NSString *string = #"abc #tag1 def #tag2.";
NSMutableArray *tags = [NSMutableArray array];
[regex enumerateMatchesInString:string options:0 range:NSMakeRange(0, string.length)
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSRange range = [result range];
NSString *tag = [string substringWithRange:range];
[tags addObject:tag];
}];
NSLog(#"%#", tags);
Output:
(
"#tag1",
"#tag2"
)
I have an NSString as:
"<a href='javascript:void(null)' onclick='handleCommandForAnchor(this, 10);return false;'>12321<\/a>"
I need to extract the 12321 near the end of the NSString from it and store.
First I tried
NSString *shipNumHtml=[mValues objectAtIndex:1];
NSInteger htmlLen=[shipNumHtml length];
NSString *shipNum=[[shipNumHtml substringFromIndex:htmlLen-12]substringToIndex:8];
But then I found out that number 12321 can be of variable length.
I can't find a method like java's indexOf() to find the '>' and '<' and then find substring with those indices. All the answers I've found on SO either know what substring to search for or know the location if the substring. Any help?
I don't usually advocate using Regular expressions for parsing HTML contents but it seems a regex matching >(\d+)< would to the job in this simple string.
Here is a simple example:
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#">(\\d+)<"
options:0
error:&error];
// Handle error != nil
NSTextCheckingResult *match = [regex firstMatchInString:string
options:0
range:NSMakeRange(0, [string length])];
if (match) {
NSRange matchRange = [match rangeAtIndex:1];
NSString *number = [string substringWithRange:matchRange]
NSLog(#"Number: %#", number);
}
As #HaneTV says, you can use the NSString method rangeOfString to search for substrings. Given that the characters ">" and "<" appear in multiple places in your string, so you might want to take a look at NSRegularExpression and/or NSScanner.
that may help on you a bit, I've just tested:
NSString *_string = #"<a href='javascript:void(null)' onclick='handleCommandForAnchor(this, 10);return false;'>12321</a>";
NSError *_error;
NSRegularExpression *_regExp = [NSRegularExpression regularExpressionWithPattern:#">(.*)<" options:NSRegularExpressionCaseInsensitive error:&_error];
NSArray *_matchesInString = [_regExp matchesInString:_string options:NSMatchingReportCompletion range:NSMakeRange(0, _string.length)];
[_matchesInString enumerateObjectsUsingBlock:^(NSTextCheckingResult * result, NSUInteger idx, BOOL *stop) {
for (int i = 0; i < result.numberOfRanges; i++) {
NSString *_match = [_string substringWithRange:[result rangeAtIndex:i]];
NSLog(#"%#", _match);
}
}];
Say given an NSString:
#"[myLabel]-10-[youImageView]"
I need an array of:
#[#"myLabel", #"yourImageView"]
How do I do it?
I thought about going through the string and check each '[' and ']', get string inside them, but is there any other better way?
Thanks
You can use regular expressions:
NSString *string = #"[myLabel]-10-[youImageView]";
// Regular expression to find "word characters" enclosed by [...]:
NSString *pattern = #"\\[(\\w+)\\]";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:0
error:NULL];
NSMutableArray *list = [NSMutableArray array];
[regex enumerateMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
// range = location of the regex capture group "(\\w+)" in the string:
NSRange range = [result rangeAtIndex:1];
[list addObject:[string substringWithRange:range]];
}
];
NSLog(#"%#", list);
Output:
(
myLabel,
youImageView
)
Would this work for you?
NSCharacterSet *aSet = [NSCharacterSet characterSetWithCharactersInString:#"]-10["];
NSArray *anArray = [aString componentsSeparatedByCharactersInSet:aSet];