Parse html NSString with REGEX [duplicate] - iphone

This question already has answers here:
Convert first number in an NSString into an Integer?
(6 answers)
Objective-C: Find numbers in string
(7 answers)
Closed 10 years ago.
I have NSString with couple strings like this that the 465544664646 is change between them :
data-context-item-title="465544664646"
How i parse the 465544664646 string to a Array ?
Edit
NSRegularExpression* myRegex = [[NSRegularExpression alloc] initWithPattern:#"(?i)(data-context-item-title=\")(.+?)(\")" options:0 error:nil];
[myRegex enumerateMatchesInString:responseString options:0 range:NSMakeRange(0, [responseString length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop) {
NSRange range = [match rangeAtIndex:1];
NSString *string =[responseString substringWithRange:range];
NSLog(string);
}];

Try this one:
NSString *yourString=#"data-context-item-title=\"465544664646\" data-context-item-title=\"1212121212\"";
NSMutableArray *substrings = [NSMutableArray new];
NSScanner *scanner = [NSScanner scannerWithString:yourString];
[scanner scanUpToString:#"\"" intoString:nil];
while(![scanner isAtEnd]) {
NSString *tempString;
[scanner scanString:#"\"" intoString:nil];
if([scanner scanUpToString:#" " intoString:&tempString]) {
[substrings addObject:tempString];
}
[scanner scanUpToString:#"\"" intoString:nil];
}
//NSLog(#"->%#",substrings); //substrings contains all numbers as string.
for (NSString *str in substrings) {
NSLog(#"->%ld",[str integerValue]); //converted each number to integer value, if you want to store as NSNumber now you can store each of them in array
}

Something like this?
-(NSString *)stringFromOriginalString:(NSString *)origin betweenStartString: (NSString*)start andEndString:(NSString*)end {
NSRange startRange = [origin rangeOfString:start];
if (startRange.location != NSNotFound) {
NSRange targetRange;
targetRange.location = startRange.location + startRange.length;
targetRange.length = [origin length] - targetRange.location;
NSRange endRange = [origin rangeOfString:end options:0 range:targetRange];
if (endRange.location != NSNotFound) {
targetRange.length = endRange.location - targetRange.location;
return [origin substringWithRange:targetRange];
}
}
return nil;
}

You can use
- (NSArray *)componentsSeparatedByString:(NSString *)separator
method like
NSArray *components = [#"data-context-item-title="465544664646" componentsSeparatedByString:#"\""];
Now you should got the string at 2. index
[components objectAtIndex:1]
Now you can create array from that string using the method here
NSString to NSArray

Related

Separate words from a NSString which are preceded by a hashtag

I have a NSString, for example:
"Had a #great time at the #party last night."
I want to separate this into an array, as so:
"Had a "
"#great"
" time at the "
"#party"
" last night."
How could i do this?
NSString *str = #"Had a #great time at the #party last night.";
NSMutableArray *arr = [[NSMutableArray alloc] init];
NSArray *array = [str componentsSeparatedByString:#"#"];
NSMutableString *retStr= [[NSMutableString alloc] initWithString:[array objectAtIndex:0]];
[arr addObject:retStr];
for(int i=1 ; i<[array count];i++)
{
NSArray *array1 = [[array objectAtIndex:i] componentsSeparatedByString:#" "];
{
NSMutableString *retStr= [[NSMutableString alloc]init];
for (int i = 0;i< [array1 count]; i++)
{
if(i==0)
{
[retStr appendFormat:#" #%# ",[array1 objectAtIndex:i]];
[arr addObject:retStr];
retStr= [[NSMutableString alloc]init];
}
else
{
[retStr appendFormat:#"%# ",[array1 objectAtIndex:i]];
}
}
[arr addObject:retStr];
}
}
NSLog(#"%#",arr);
You will get the corect output as you want
try like this it'l helps you,
NSString *str=#"how are #you #friend";
NSArray *arr=[str componentsSeparatedByString:#" "];
NSPredicate *p = [NSPredicate predicateWithFormat:#"not SELF contains '#'"];
NSArray *b = [arr filteredArrayUsingPredicate:p];
NSLog(#"%#",b);
above predicate will returns the words which are not containg '#' symbol
NSPredicate *p = [NSPredicate predicateWithFormat:#"not SELF like '#*'"];
it'l returns the words which are not started with the letter '#'
O/P:-
(
how,
are
)
EDIT:-
NSString *str=#"how are #you #friend";
NSArray *arr=[str componentsSeparatedByString:#"#"];
NSMutableArray *result=[[NSMutableArray alloc]initWithObjects:[arr objectAtIndex:0], nil];
for(int i=1;i<[arr count];i++){
[result addObject:[NSString stringWithFormat:#"#%#",[arr objectAtIndex:i]]];
}
NSLog(#"%#",result);
O/P:-
(
"how are ",
"#you ",
"#friend"
)
Try to use this regexp: (#.+?\\b)|(.+?(?=#|$))
It find words which begins with hashtag and subsequences which ends with hashtag
NSString * string = #"Had a #great time at the #party last night.";
NSError * error = nil;
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:#"((#.+?\\b)|(.+?(?=#|$)))"
options:0
error:&error];
NSArray * matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult* match in matches ) {
NSLog(#"%#", [string substringWithRange:[match range]]);
}
Output:
2013-04-29 16:57:51.688 Had a
2013-04-29 16:57:51.689 #great
2013-04-29 16:57:51.690 time at the
2013-04-29 16:57:51.691 #party
2013-04-29 16:57:51.692 last night.
If you want to do it efficiently in a single pass on the string you can try something like (scratch code - test for bugs/boundary cases etc...):
int main (int argc, const char * argv[])
{
NSString *msg = #"Had a #great time at the #party last night.";
Boolean inTag = NO;
NSMutableArray *segments = [[NSMutableArray alloc] init];
NSUInteger idx = 0;
NSUInteger i=0;
for (; i < [msg length]; i++)
{
unichar ch = [msg characterAtIndex:i];
if (inTag && ch == ' ')
{
[segments addObject:[msg substringWithRange:NSMakeRange(idx, i - idx)]];
idx = i;
inTag = NO;
}
if (ch == '#')
{
[segments addObject:[msg substringWithRange:NSMakeRange(idx, i - idx)]];
idx = i;
inTag = YES;
}
}
if (i > idx)
{
[segments addObject:[msg substringWithRange:NSMakeRange(idx, i - idx - 1)]];
}
for(NSString *seg in segments)
{
NSLog(#"%#", seg);
}
}
This outputs:
2013-04-29 08:34:34.984 Craplet[95591:707] Had a
2013-04-29 08:34:34.986 Craplet[95591:707] #great
2013-04-29 08:34:34.986 Craplet[95591:707] time at the
2013-04-29 08:34:34.987 Craplet[95591:707] #party
2013-04-29 08:34:34.987 Craplet[95591:707] last night
Try this:
for (int i=0;i<[YourArray count];i++) {
NSString * mystr=[YourArray objectAtIndex:i];
NSString *temp=[mystr substringToIndex:1];
if (![temp isEqualToString:#"#"]) {
//add your string in new array and use this arry.....
}
}
try this code
for (int i=0;i<[YourArray count];i++) {
NSString * str=[YourArray objectAtIndex:i];
NSString *myString=[str substringToIndex:1];
NSString *stringfinal = [myString
stringByReplacingOccurrencesOfString:#"#" withString:#""];
}
Try using regular expressions. With this code you'll be able to extract the hashtags:
NSString * string = #"Had a #great time at the #party last night.";
NSError * error = nil;
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:#"((?:#){1}[\\w\\d]{1,140})" options:0 error:&error];
NSArray * matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
for ( NSTextCheckingResult* match in matches )
{
NSString * hashtag = [string substringWithRange:[match range]];
NSLog(#"match: %#", hashtag);
}
With this, you'll be able to build up the array result you're looking for.
Try
NSString *string = #"Had a #great time at the #party last night.";
NSArray *components = [string componentsSeparatedByString:#" "];
NSMutableArray *formattedArray = [NSMutableArray array];
NSMutableString *mutableString = [NSMutableString string];
for (NSString *string in components)
{
if (![string hasPrefix:#"#"]){
if (!mutableString){
mutableString = [NSMutableString string];
}
[mutableString appendFormat:#" %#",string];
}else{
if (mutableString) {
[formattedArray addObject:mutableString];
mutableString = nil;
}
[formattedArray addObject:string];
}
}
if (mutableString) {
[formattedArray addObject:mutableString];
}
NSLog(#"%#",formattedArray);
EDIT :
(
" Had a",
"#great",
" time at the",
"#party",
" last night."
)
One-pass solution with NSScanner
NSString *string = #"Had a #great time at the #party last night.";
NSMutableArray *array = [#[] mutableCopy];
NSScanner *scanner = [NSScanner scannerWithString:string];
while (![scanner isAtEnd]) {
NSString *s;
[scanner scanUpToString:#"#" intoString:&s];
if(s) [array addObject:s];
s = nil;
[scanner scanUpToString:#" " intoString:&s];
if(s) [array addObject:s];
}
result:
(
"Had a ",
"#great",
"time at the ",
"#party",
"last night."
)
if you want to preserve the leading whitespace, alter it slightly to
NSString *string = #"Had a #great time at the #party last night.";
NSMutableArray *array = [#[] mutableCopy];
NSScanner *scanner = [NSScanner scannerWithString:string];
BOOL firstSegment = YES;
while (![scanner isAtEnd]) {
NSString *s;
[scanner scanUpToString:#"#" intoString:&s];
if(s) [array addObject: (!firstSegment) ? [#" " stringByAppendingString:s] : s];
s = nil;
[scanner scanUpToString:#" " intoString:&s];
if(s) [array addObject:s];
firstSegment = NO;
}
result:
(
"Had a ",
"#great",
" time at the ",
"#party",
" last night."
)

Remove Html Format from String

I have been trying to format a string in my text view but I cant work it out. Im very new to xcode.
Am i missing something in this file? I have been looking through stack and this is how you do it..but its not working.
- (NSString *)stripTags:(NSString *)str
{
NSMutableString *html = [NSMutableString stringWithCapacity:[str length]];
NSScanner *scanner = [NSScanner scannerWithString:str];
scanner.charactersToBeSkipped = NULL;
NSString *tempText = nil;
while (![scanner isAtEnd])
{
[scanner scanUpToString:#"<" intoString:&tempText];
if (tempText != nil)
[html appendString:tempText];
[scanner scanUpToString:#">" intoString:NULL];
if (![scanner isAtEnd])
[scanner setScanLocation:[scanner scanLocation] + 1];
tempText = nil;
}
return html;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *str = newsArticle;
descTextView.text = [NSString stringWithString:str];
// Do any additional setup after loading the view from its nib.
}
This code is a modified version of what was posted as an answer to a similar question here https://stackoverflow.com/a/4886998/283412. This will take your HTML string and strip out the formatting.
-(void)myMethod
{
NSString* htmlStr = #"<some>html</string>";
NSString* strWithoutFormatting = [self stringByStrippingHTML:htmlStr];
}
-(NSString *)stringByStrippingHTML:(NSString*)str
{
NSRange r;
while ((r = [str rangeOfString:#"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
{
str = [str stringByReplacingCharactersInRange:r withString:#""];
}
return str;
}
You are trying to put HTML into a label. You want to use a UIWebView.
#try this one
-(NSString *) stringByStrippingHTML:(NSString *)HTMLString {
NSRange r;
while ((r = [HTMLString rangeOfString:#"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
HTMLString = [HTMLString stringByReplacingCharactersInRange:r withString:#""];
return HTMLString;
}

nsstring replace string in range

I have a string with certain pattern. I need to search for the pattern and replace the string inside that pattern. For eg :
NSString *string = #"{Hello} ({World}) ({How}) ({Are}) ({You})";
NSString *result = nil;
// Determine "{" location
NSRange startRange = [string rangeOfString:#"{" options:NSCaseInsensitiveSearch];
if (startRange.location != NSNotFound)
{
// Determine "}" location according to "{" location
NSRange endRange;
endRange.location = startRange.length + startRange.location;
endRange.length = [string length] - endRange.location;
endRange = [string rangeOfString:#"}" options:NSCaseInsensitiveSearch range:endRange];
if (endRange.location != NSNotFound)
{
// bracets found: retrieve string between them
startRange.location += startRange.length;
startRange.length = endRange.location - startRange.location;
result = [string substringWithRange:startRange];
}
}
Here I am able to extract the first substring that is between "{ }" ie - "Hello" but I also need to continue the check and want to extract other strings.
Try this one:
NSString *string = #"{Hello} ({World}) ({How}) ({Are}) ({You})";
//NSString *result = nil;
// Determine "{" location
NSArray *array=[string componentsSeparatedByString:#"{"];
for(NSString *str in array){
NSString *newString=[[str componentsSeparatedByString:#"}"] objectAtIndex:0];
NSLog(#"%#",newString);
}
try this :
NSString *string = #"{Hello} ({World}) ({How}) ({Are}) ({You})";
NSMutableString *result = [[NSMutableString alloc] init];
NSArray *tempArray = [[string componentsSeparatedByString:#" "] mutableCopy];
for (int i=0; i < [tempArray count]; i++)
{
NSString *tempStr = [tempArray objectAtIndex:i];
NSRange startRange = [tempStr rangeOfString:#"{" options:NSCaseInsensitiveSearch];
if (startRange.location != NSNotFound)
{
// Determine "}" location according to "{" location
NSRange endRange;
endRange.location = startRange.length + startRange.location;
endRange.length = [tempStr length] - endRange.location;
endRange = [tempStr rangeOfString:#"}" options:NSCaseInsensitiveSearch range:endRange];
if (endRange.location != NSNotFound)
{
// bracets found: retrieve string between them
startRange.location += startRange.length;
startRange.length = endRange.location - startRange.location;
//result = [tempStr substringWithRange:startRange];
[result appendString:[NSString stringWithFormat:#"%# ",[tempStr substringWithRange:startRange]]];
NSLog(#"%# ",result);
}
}
}
Take care for release for tempArray and result
I happen to have this code lying around. I think it does exactly what you want. I implemented it as a category on NSString. You use it like this:
NSString *template = #"{Hello} ({World}) ({How}) etc etc";
NSDictionary *vars = [NSDictionary dictionaryWithObjectsAndKeys:
#"Bonjour", #"Hello",
#"Planet Earth", #"World",
#"Como", #"How",
// etc.
nil];
NSString *expandedString = [template stringByExpandingTemplateWithVariables:vars];
// expandedString is #"Bonjour (Planet Earth) (Como) etc etc"
Here's the code.
File NSString+TemplateExpansion.h
#import <Foundation/Foundation.h>
#interface NSString (TemplateExpansion)
- (NSString *)stringByExpandingTemplateWithVariables:(NSDictionary *)dictionary;
#end
File NSString+TemplateExpansion.m
#import "NSString+TemplateExpansion.h"
#implementation NSString (TemplateExpansion)
- (NSString *)stringByExpandingTemplateWithVariables:(NSDictionary *)dictionary
{
NSUInteger myLength = self.length;
NSMutableString *result = [NSMutableString stringWithCapacity:myLength];
NSRange remainingRange = NSMakeRange(0, myLength);
while (remainingRange.length > 0) {
NSRange leftBraceRange = [self rangeOfString:#"{" options:0 range:remainingRange];
if (leftBraceRange.location == NSNotFound)
break;
NSRange afterLeftBraceRange = NSMakeRange(NSMaxRange(leftBraceRange), myLength - NSMaxRange(leftBraceRange));
NSRange rightBraceRange = [self rangeOfString:#"}" options:0 range:afterLeftBraceRange];
if (rightBraceRange.location == NSNotFound)
break;
NSRange beforeLeftBraceRange = NSMakeRange(remainingRange.location, leftBraceRange.location - remainingRange.location);
[result appendString:[self substringWithRange:beforeLeftBraceRange]];
remainingRange = NSMakeRange(NSMaxRange(rightBraceRange), myLength - NSMaxRange(rightBraceRange));
NSRange keyRange = NSMakeRange(NSMaxRange(leftBraceRange), rightBraceRange.location - NSMaxRange(leftBraceRange));
NSString *key = [self substringWithRange:keyRange];
NSString *value = [dictionary objectForKey:key];
if (value)
[result appendString:value];
}
[result appendString:[self substringWithRange:remainingRange]];
return result;
}
#end

Replace multiple groups of characters in an NSString

I want to replace several different groups of characters in one NSString. Currently I am doing it with several repeating methods, however I am hoping there is a way of doing this in one method:
NSString *result = [html stringByReplacingOccurrencesOfString:#"<B&" withString:#" "];
NSString *result2 = [result stringByReplacingOccurrencesOfString:#"</B>" withString:#" "];
NSString *result3 = [result2 stringByReplacingOccurrencesOfString:#"gt;" withString:#" "];
return [result3 stringByReplacingOccurrencesOfString:#" Description " withString:#""];
I don't think there is anything in the SDK, but you could at least use a category for this so you can write something like this:
NSDictionary *replacements = [NSDictionary dictionaryWithObjectsAndKeys:
#" ", #"<B&",
#" ", #"</B>",
#" ", #"gt;"
#"" , #" Description ",
nil];
return [html stringByReplacingStringsFromDictionary:replacements];
... by using something like the following:
#interface NSString (ReplaceExtensions)
- (NSString *)stringByReplacingStringsFromDictionary:(NSDictionary *)dict;
#end
#implementation NSString (ReplaceExtensions)
- (NSString *)stringByReplacingStringsFromDictionary:(NSDictionary *)dict
{
NSMutableString *string = [self mutableCopy];
for (NSString *target in dict) {
[string replaceOccurrencesOfString:target withString:[dict objectForKey:target]
options:0 range:NSMakeRange(0, [string length])];
}
return [string autorelease];
}
#end
In modern Objective C with ARC:
-(NSString*)stringByReplacingStringsFromDictionary:(NSDictionary*)dict
{
NSMutableString *string = self.mutableCopy;
for(NSString *key in dict)
[string replaceOccurrencesOfString:key withString:dict[key] options:0 range:NSMakeRange(0, string.length)];
return string.copy;
}

iphone sdk - Remove all numbers except for characters a-z from a string

In my app I want to remove numbers except characters a-z from string. How can I get only characters?
This is the short answer which doesnt need any lengthy coding
NSString *newString = [[tempstr componentsSeparatedByCharactersInSet:
[[NSCharacterSet letterCharacterSet] invertedSet]] componentsJoinedByString:#""];`
swift 3:
(tempstr.components(separatedBy:NSCharacterSet.letters.inverted)).joined(separator: "")
eg:
("abc123".components(separatedBy:NSCharacterSet.letters.inverted)).joined(separator: "")
NSString *stringToFilter = #"filter-me";
NSMutableString *targetString = [NSMutableString string];
//set of characters which are required in the string......
NSCharacterSet *okCharacterSet = [NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyz"];
for(int i = 0; i < [stringToFilter length]; i++)
{
unichar currentChar = [stringToFilter characterAtIndex:i];
if([okCharacterSet characterIsMember:currentChar])
{
[targetString appendFormat:#"%C", currentChar];
}
}
NSLog(targetString);
[super viewDidLoad];
}
this was an answer given to me and works fine
I found an answer:
from remove-all-but-numbers-from-nsstring
NSString *originalString = #"(123) 123123 abc";
NSLog(#"%#", originalString);
NSMutableString *strippedString = [NSMutableString
stringWithCapacity:originalString.length];
NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet
characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyz"];
while ([scanner isAtEnd] == NO) {
NSString *buffer;
if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
[strippedString appendString:buffer];
} else {
[scanner setScanLocation:([scanner scanLocation] + 1)];
}
}
NSLog(#"%#", strippedString);