I have a dynamic string suppose
NSString *originalString = #"Hello my Phone : 123123123 abc 987";
In the above string first i have to check were numbers are present inside the string which i got it by doing below code :-
NSString *newString = [[MessageStr componentsSeparatedByCharactersInSet:
[[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
componentsJoinedByString:#""];
result i got in newString is 123123123987
But my problem is not getting out numbers from string, i just want to add a special character after every number inside the string which is dynamic.
like i want to make my string like this :-
NSString *originalString = #"Hello my Phone : 1,2,3,1,2,3,1,2,3 abc 9,8,7";
So, please any one can suggest me, what's best possible way to achieve above string.
Thanks in advance.
I finally succeed by doing the following code :-
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:#"([0-9])" options:0 error:NULL];
NSString *newString = [regexp stringByReplacingMatchesInString:MessageStr options:0 range:NSMakeRange(0, MessageStr.length) withTemplate:#"$0,"];
NSLog(#"Changed %#", newString);
Thanks #nsgulliver
by posting answer in the link :-
Related
for(int i= 0 ;i<[urlsArrray count]; i++)
{
NSString *urlString = [urlsArrray objectAtIndex:i];
NSString *escapedUrlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:escapedUrlString];
NSString *urlstring1 = [url absoluteString];
NSArray *parts = [urlstring1 componentsSeparatedByString:#"/"];
NSString *fileName = [parts objectAtIndex:[parts count]-1];
NSMutableString *tempString = [NSMutableString stringWithString:fileName];
// [tempString replaceCharactersInRange:[tempString rangeOfString:#"%20"] withString:#" "];
NSLog(#"file name in temp string: %# word name: %#", tempString, wordNameDB);
NSRange match = [tempString rangeOfString:wordNameDB];
if(match.location != NSNotFound)
{
NSLog(#"match found at %u", match.location);
isAvailable = YES;
break;
}
Hi friends, now my problem is i am getting file name from server..., if file name is having any spaces then it replace '%20' ( i.e ex: "hello world" is actual name but i am getting file name like: "hello%20world") .
1. I am not sure all file names having spaces.
2. And also i am not sure a file may have only one space
so first i have to check the file is having spaces or not, if have then i want to replace all "%20" with #" " string. Please give me any suggestions or code snippets.
OR " THERE IA ANY OTHER WAY TO READ FILE NAMES WITHOUT GETTING '%20' IN THE PLACE OF SPACE(#" ")..... thank you
If you have your file name stored in fileName param, you can use the following:
fileName = [fileName stringByReplacingOccurrencesOfString:#"%20" withString:#" "];
The above code will replace all "%20" with " ". If there are no "%20" in the fileName, you will get back the same string.
Correction:
I was confused with stringByAddingPercentEscapesUsingEncoding mentioned in code and thought you have already used stringByReplacingPercentEscapesUsingEncoding. If you are not using stringByReplacingPercentEscapesUsingEncoding method, you should use that in this case. The above code is useful, only if that is not able to remove any particular string which you want to replace.
What you need is replacing the escape charcters, according to the encoding.
Use this and all your spaces and other URL encoded characters will be converted to what you need.
[#"yourString" stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
THERE IA ANY OTHER WAY TO READ FILE NAMES WITHOUT GETTING '%20' IN THE PLACE OF SPACE(#" ")
Yes, use this:
NSString *newString = [yourstring stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Use this to remove spaces ..
urlString = [urlString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
You seem to already have a valid NSURL object representing the file. Getting the filename from a URL is easy:
...
NSURL *url = [NSURL URLWithString:escapedUrlString];
NSString *path = [url path];
NSString *filename = [path lastPathComponent];
No fiddling with unescaping percent escapes, URL parsing, and other error prone stuff.
I have a very big NSString, which holds around 1500 characters in it. In this string I need to extract a phone number, which may change frequently, as it is a dynamic data. The phone number will be in the format of 251-221-2000, how can I extract this?
Check out this previous question on regular expressions and NSString.
Search through NSString using Regular Expression
In your case an appropriate regular expression would be #"\\d{3}-\\d{3}-\\d{4}".
This sounds like a perfect candidate for a regular expression. You can use the NSRegularExpression class to achieve this. You can test your regular expression at http://www.regextester.com
NSString *yourString = #"Your 1500 characters string ";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"\d{3}-\d{3}-\d{4}"
options:NSRegularExpressionCaseInsensitive
error:&error];
[regex enumerateMatchesInString:yourString options:0 range:NSMakeRange(0, [yourString length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
// your code to handle matches here
}];
Let me know it is working or not.
i need to send smiley to other user through iphone app ,so i need to replace \ string with some unique string in obj c.
here if your string is #"\ud83d\ude04" then it is give error "Invalid Character" so put this ' special character and then use it ..
NSString *str = #"\'ud83d\'ude04";//// here if your string is #"\ud83d\ude04" then it is give error "Invalid Character" so put this ' special character and then use it
NSString *smileWithString = [str stringByReplacingOccurrencesOfString:#"\'" withString:#":)"];
[smileWithString retain];
NSLog(#"\n\n SmileString %# Str %#",smileWithString);
Update:
Here’s how to convert NSString to NSData – it’s really simple:
NSString *myString = #"Some String";
NSData *myData = [myString dataUsingEncoding:NSUTF8StringEncoding];
And what about the reverse conversion, i.e. how to convert NSData to NSString? Here’s one quick way:
NSString *myString = [NSString stringWithFormat:#"%.*s",[myData length], [myData bytes]];
Use encoding of NSString and when need to use or show string decode it.
Refer base64-encoding link.
Your looking for stringByReplacingOccurrencesOfString that should do the trick.
NSString *newString = [oldString stringByReplacingOccurrencesOfString:#"\" withString:#"uniqueString"];
I have an NSMutable dictionary that contains file IDs and their filename+extension in the simple form of fileone.doc or filetwo.pdf. I need to determine what type of file it is to correctly display a related icon in my UITableView. Here is what I have done so far.
NSString *docInfo = [NSString stringWithFormat:#"%d", indexPath.row]; //Determine what cell we are formatting
NSString *fileType = [contentFiles objectForKey:docInfo]; //Store the file name in a string
I wrote two regex to determine what type of file I'm looking at, but they never return a positive result. I haven't used regex in iOS programming before, so I'm not entirely sure if I'm doing it right, but I basically copied the code from the Class Description page.
NSError *error = NULL;
NSRegularExpression *regexPDF = [NSRegularExpression regularExpressionWithPattern:#"/^.*\\.pdf$/" options:NSRegularExpressionCaseInsensitive error:&error];
NSRegularExpression *regexDOC = [NSRegularExpression regularExpressionWithPattern:#"/^.*\\.(doc|docx)$/" options:NSRegularExpressionCaseInsensitive error:&error];
NSUInteger numMatch = [regexPDF numberOfMatchesInString:fileType options:0 range:NSMakeRange(0, [fileType length])];
NSLog(#"How many matches were found? %#", numMatch);
My questions would be, is there an easier way to do this? If not, are my regex incorrect? And finally if I have to use this, is it costly in run time? I don't know what the average amount of files a user will have will be.
Thank you.
You're looking for [fileType pathExtension]
NSString Documentation: pathExtension
//NSURL *url = [NSURL URLWithString: fileType];
NSLog(#"extension: %#", [fileType pathExtension]);
Edit you can use pathExtension on NSString
Thanks to David Barry
Try this :
NSString *fileName = #"resume.doc";
NSString *ext = [fileName pathExtension];
Try this, it works for me.
NSString *fileName = #"yourFileName.pdf";
NSString *ext = [fileName pathExtension];
Documentation here for NSString pathExtension
Try using [fileType pathExtension] to get the extension of the file.
In Swift 3 you could use an extension:
extension String {
public func getExtension() -> String? {
let ext = (self as NSString).pathExtension
if ext.isEmpty {
return nil
}
return ext
}
}
> (2009 RX7)</font></td>
>monospace" size="-1">214869 (2007 PAZ)</font></td>
>monospace" size="-1"> 4155 Accord</font></td>
I wonder if someone could offer me a little help, I have a list of NSString items (See Above) that I want to parse some data from. My problem is that there are no tags that I can use within the strings nor do the items I want have fixed positions. The data I want to extract is:
2009 RX7
2007 PAZ
4155 Accord
My thinking is that its going to be easier to parse from the right hand end, remove the </font></td> and then use ";" to separate the data items:
(2009  RX7)
(2007  PAZ)
4155  Accord
which can them be cleaned up to match the example given. Any pointers on doing this or working through from the right would be very much appreciated.
Personally I think you are better off with a regex. So my solution would be:
Regex of: ([0-9]+)[^;]+;([A-Za-z0-9]+)
Which for all the example text provides 3 matches. ie for:
(2009 RX7)</font></td>
0: 2009 RX7)<
1: 2009
2: RX7
I haven't coded this up, but did test the Regex at www.regextester.com
Regex's are implemented via NSRegularExpression and are available in iOS 4.0 and later.
Edit
Given that this appears to be a web scraping application, you never know when those pesky HTML code monkeys will change their output and break your carefully crafted matching methodology. As such I would change my regex to:
([0-9]+)([^;]+;)+([A-Za-z0-9]+)
Which adds an extra group, but allows for any number of elements between the number and the string.
Try this code:
NSString *str = #"> (2009 RX7)</font></td>";
NSRange fontRange = [str rangeOfString:#"</Font>" options:NSBackwardsSearch];
NSRange lastSemi = [str rangeOfString:#";" options:NSBackwardsSearch range:NSMakeRange(0, fontRange.location-1)];
NSRange priorSemi = [str rangeOfString:#";" options:NSBackwardsSearch range:NSMakeRange(0, lastSemi.location-1)];
NSString *yourString = [str substringWithRange:NSMakeRange(priorSemi.location+1, fontRange.location-1)];
The key element here is the NSBackwardsSearch search option.
This should do the trick:
NSString *s = #">monospace\" size=\"-1\"> 4155 Accord</font></td>";
NSArray *strArray = [s componentsSeparatedByString:#";"];
// you're interested in last two objects
NSArray *tmp = [strArray subarrayWithRange:NSMakeRange(strArray.count - 2, 2)];
In tmp you'll have something like:
"4155 ",
"Accord</font></td>"
strip unneeded chars and you're all set.
Using NSRegularExpression:
NSRegularExpression *regex;
NSTextCheckingResult *match;
NSString *pattern = #"([0-9]+) ([A-Za-z0-9]+)[)]?</font></td>";
NSString *string = #"> (2009 RX7)</font></td>";
regex = [NSRegularExpression
regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:nil];
match = [regex firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
NSLog(#"'%#'", [string substringWithRange:[match rangeAtIndex:1]]);
NSLog(#"'%#'", [string substringWithRange:[match rangeAtIndex:2]]);
NSLog output:
'2009'
'RX7'