Separating Area Code from Phone Number - iOS - ios

How can I parse out the area code from any given phone number? For example, if I enter in 208-399-2777, the 208 is the area code in the United States. However, in Brazil, the phone number 78 5239-6822 has a 2-digit area code.
Does NSTextCheckingResult provide any of this functionality?

Depending on the complexity of your problem where tinkering with the string may not work and you may want to know more about the area code, check out Google's libphonenumber https://code.google.com/p/libphonenumber/, there is a wrapper for Objective C https://github.com/iziz/libPhoneNumber-iOS.

This will get the first "set" of numbers in the phone number string
NSString *pattern = #"^\\d+";
NSRegularExpression* regex = [[NSRegularExpression alloc] initWithPattern:pattern
options:0
error:nil];
Explanation:
^ matches the beginning of a string
\d+ matches one or more numbers
Note: If your phone numbers are formatted without spaces (e.g., 1234567890) it will not work.

Related

using Regular Expression in objective C

It's the first time trying to use Regular Expression. I am trying to match Australian Post code(i.e 4 digit) , but my noOFMatches gets no . of digits +1 (9 in this case)in it. I know it's something silly that i cannot figure out. Pls suggest.
I feel if I pass 4 digit nos. in postcode then noOfMatches should get 1 . is that correct?
NSString *postCode = #"12345676";
NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:#"(|d{4})" options:NSRegularExpressionCaseInsensitive error:nil];
int noOfMatches = [ regularExpression numberOfMatchesInString:field.text options:0 range:NSMakeRange(0, [postCode length])];
You're on the right track, although the pattern you've used isn't correct and that's why it returns 9 matches.
It's an easy fix:
([0-9]{4})
or
(\\d{4})
Should give you the correct result: 2
You should use a regex tester, eg http://regexpal.com/
Native iOS regex is ridiculously clumsy and lengthy. If you work with regex alot, I'd recommend using a library, such as https://github.com/bendytree/Objective-C-RegEx-Categories

NSRegularExpression to match a certain pattern

Backgroud:
I have a response like so (please note the new lines):
HTTP/1.1 200 OK
CACHE-CONTROL: max-age = 180
EXT:
LOCATION: http://172.16.16.16:80/upnp.jsp
SERVER: Linux/2.6.32.24 UPNP/1.0 ZD3025/9.5.1.0
ST: upnp:rootdevice
USN: uuid:6e4bb543-fff6-4384-a4be-::upnp:rootdevice
I would like to match the Server line which is:
Linux/2.6.32.24 UPNP/1.0 ZD3025/9.5.1.0
Implementation:
I don't care about any character in the above given response EXCEPT for the characters Linux, UPNP and ZD (in that order).
So I am using .* to match any number of characters, numbers, special chars.
-(void) regexCompareForUPnP:(NSString *) string {
NSError * err = nil;
//Building expression
NSString *expression = #"^.*Linux.*UPNP.*ZD.*$";
NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:expression options:0 error:&err];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:string
options:0
range:NSMakeRange(0, [string length])];
NSLog(#"Matches found: %d", numberOfMatches);
}
So far, Matches found: 0.
Question:
So, in short does this:
NSString *expression = #"^.*Linux.*UPNP.*ZD.*$";
Match this:
Linux/2.6.32.24 UPNP/1.0 ZD3025/9.5.1.0
EDIT:
Thank you omz that worked perfectly.
Now I am trying to match the upnp.jsp (in the LOCATION line) alongwith what I was trying to match before. So I tried this:
NSString *expression = #"^.*upnp.jsp\n.*Linux.*UPNP.ZD.$";
That does not work. Appreciate your help..
I'm not familiar with this regex library. Based on what you're trying to match, however, it may be to do with newlines between OS's and individual programs.
Try this: *expression = #"upnp.jsp\r?\n[^\n]*?Linux[^\n]*?UPNP[^\n]*?ZD"
A few other changes made from what you're trying as well;
I've replaced .* with [^\n]*? for two reasons:
I'm not sure how this library deals with .*, but using that is typically inefficient in comparison to something more speicific such as looking for a non-greedy set of characters that aren't a new line. The difference between .* and .*? depends on the regex engine. In most regex engines I work with at least, .* is by default greedy; i.e. it will capture as much data as it can while still having the expression find a match. Using the non-greedy version, .*?, means that the regex will capture only as much as it needs to to satisfy the whole expression. This is particularly evident in an example I'll expand on at the end.
I removed the surrounding ^$ because when they are appended and prepended with .* they only work towards increasing processing time (unless you were using matching groups, which you aren't). If you were doing ^(.*)upnp or ^(.*upnp) and then using the contents of the matched group, there could be purpose in having the initial ^.*.
As for greedy/non-greedy, the difference becomes evident when trying to match data between a set of double quotes ". For the sake of simplicity, I won't deal with having escaped double quotes in the middle of a string you also want to capture.
Given the string: I said, "Hi." She responded with, "Hello!"
Using the greedy regex "(.*)", the matched group would be Hi." She responded with, "Hello!
Using the non-greedy regex "(.*?)", the matched group would be Hi.

iOS -- Strings -- Insert String at Specific Position

I have a long string. I'd like to take this long string, search for any occurrences of words that appear between quotes (i.e., "string"), and insert a string before the word (i.e., "x"), and a string after the word (i.e., "y").
Any solutions would be most appreciated! Thanks!
I see that I could use the following to grab the text between the quotes:
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"([\"])
(?:\\\\\\1|.)*?\\1" options:0 error:&error];
NSRange range = [regex rangeOfFirstMatchInString:myString options:0 range:NSRangeMake(0,
[myString length]];
However, now I need to replace the text that is inside the quotations, inserting the html tags "bold" before and "/bold" after. Is there anyway for me to do this? Also, if there are multiple occurrences of quoted text in a given string, how would I use the above code to cycle through the string to get modify each piece of quoted text one-by-one?
I came across this post ([click here]]1 but I'm not quite sure how to modify the sample code to achieve the result I want. Any help would be great!
I will refer you to this page: Shortcuts in Objective-C to concatenate NSStrings
The page talks about adding strings together by using two NSMutable strings and adding one to both, which seems to be the preferable of the two it gives. Unfortunately, there is no operation to add two or more strings together (which really sucks).
Try this:
NSString *original=#"The quick 'brown fox' The quick 'brown fox' ";
NSString *target=[original stringByReplacingOccurrencesOfString:#"'brown fox'" withString:#"<b>brown fox</b>"];

Format textfield for CPF and CNPJ

How should I handle text formatting in iOS? I'm not talking about Currency or Decimal styles. Since iOS doesn't have setFormat(), it's kind of complicated.
Two examples of the format I want: 123.456.789-10 and 123.456.789/1000-00.
My aim is to format a text field as the user types. Like any normal site does when, for example, you type a phone number. It doesn't comes from a model or anything. The user just needs to type the numbers and when necessary I'll insert the ".","/" or "-".
You can use regular expressions to do formatting, like this:
NSRegularExpression *fmt = [NSRegularExpression
regularExpressionWithPattern:#"(.{1,3})(.{1,3})(.{1,3})(.{1,2})"
options:0
error:NULL];
NSMutableString *str = [NSMutableString stringWithString:#"12345678910"];
[fmt replaceMatchesInString:str
options:0
range:NSMakeRange(0, str.length)
withTemplate:#"$1.$2.$3-$4"];
This transforms the string into 123.456.789-10
In order to apply this formatting dynamically as users type, create NSRegularExpression *fmt upfront, store it in your UITextFieldDelegate, and use it in your textField:shouldChangeCharactersInRange:replacementString: method.
I created my own method a couple days ago for checking for valid temperature input. It was a bit of a pain as well because I had to check for:
-only numbers
-only one decimal point
-if there was a negative sign it had to be at the front
I ended up using [my string characterAtIndex:index]; and checking each character, since i would have no more than 4 characters.
EDIT:
Here is some pseudo code
for (every char in your string)
if(the index of the char % 3 == 2) //every third char, 0,2,5...
the char must be a . or / or -
else
the char must be a number

Telephone number format should be international,Is there any Regex for phone number validation in iPhone

Telephone number should be international and user has to enter the complete phone number with country code.
For that I need a regex for formatting the phone number.
For real regex testing use RegexKitLite.
As for the regular expression itself, something like this (from Validate Phone Numbers: A Detailed Guide) should work:
^\+(?:[0-9] ?){6,14}[0-9]$
Note that when you specify it in your code you need to escape the backslash character (\), so it would look like this:
NSString *regexString = #"^\\+(?:[0-9] ?){6,14}[0-9]$";

Resources