Convert number to phone format using regular expression - iphone

My problem is that I have some text field with number and I must to convert this number to some phone format like this one (xxx) xxx-xxxx. I have tried an regular expression with this code:
wholeText = [wholeText stringByReplacingOccurrencesOfString:#"(\\d{1,3})(\\d{0,3})(\\d{0,4})"
withString:#"($1) $2-$3"
options:NSRegularExpressionSearch
range:NSMakeRange(0, wholeText.length)];
NSLog(#"wholeText = %#", wholeText);
If I gradually enter a text in text field, NSLog output this:
wholeText = (1) -
wholeText = (12) -
wholeText = (123) -
wholeText = (123) 4-
wholeText = (123) 45-
wholeText = (123) 456-
wholeText = (123) 456-7
So my problem that I do not need brackets and hyphens if there is no number before it, i.e. closing bracket should appear after I enter 4th number and hyphen should appear after I enter 7th number.

Use this Utility
UITextField subclass that allows number input in a predefined format.
http://www.cocoacontrols.com/controls/reformattednumberfield

If you have access to lazy operators, this will do what you want (I guess, you didn't give that much details.):
/^(\d{1,3}?)(\d{1,3}?)(\d{1,4})$/
How? Lazy operators.

use below code
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
int length = [self getLength:textField.text];
//NSLog(#"Length = %d ",length);
if(length == 10)
{
if(range.length == 0)
return NO;
}
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSCharacterSet *charactersToRemove = [[ NSCharacterSet alphanumericCharacterSet ] invertedSet ];
newString = [[newString componentsSeparatedByCharactersInSet:charactersToRemove]componentsJoinedByString:#""];
NSString *expression = #"^([0-9]+)?(\\.([0-9]{1,2})?)?$";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression
options:NSRegularExpressionCaseInsensitive
error:nil];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString
options:0
range:NSMakeRange(0, [newString length])];
NSLog(#"newString::%#",newString);
if (numberOfMatches == 0)
return NO;
if(length == 3)
{
NSString *num = [self formatNumber:textField.text];
textField.text = [NSString stringWithFormat:#"(%#)",num];
if(range.length > 0)
textField.text = [NSString stringWithFormat:#"%#",[num substringToIndex:3]];
}
else if(length == 6)
{
NSString *num = [self formatNumber:textField.text];
//NSLog(#"%#",[num substringToIndex:3]);
//NSLog(#"%#",[num substringFromIndex:3]);
textField.text = [NSString stringWithFormat:#"(%#) %#-",[num substringToIndex:3],[num substringFromIndex:3]];
if(range.length > 0)
textField.text = [NSString stringWithFormat:#"(%#) %#",[num substringToIndex:3],[num substringFromIndex:3]];
}
return YES;
}
#pragma mark - Mobile Validation
-(NSString*)formatNumber:(NSString*)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"+" withString:#""];
NSLog(#"%#", mobileNumber);
int length = [mobileNumber length];
if(length > 10)
{
mobileNumber = [mobileNumber substringFromIndex: length-10];
NSLog(#"%#", mobileNumber);
}
return mobileNumber;
}
-(int)getLength:(NSString*)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"+" withString:#""];
int length = [mobileNumber length];
return length;
}
try this you will be succeed

Related

Not getting "-" "." " " while picking up a contact from phonebook from ABPerson

I want to get number as it is with "-" " " "." while picking up a contact from phone book here's my code .
My main motive is to extract the country code from the number if + is present.
Also please suggest me if there is any other way to access country code.
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier;
{
if (property == kABPersonPhoneProperty) {
ABMultiValueRef multiPhones = ABRecordCopyValue(person, kABPersonPhoneProperty);
for(CFIndex i = 0; i < ABMultiValueGetCount(multiPhones); i++) {
if(identifier == ABMultiValueGetIdentifierAtIndex (multiPhones, i)) {
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, i);
CFRelease(multiPhones);
NSString *phoneNumber = (__bridge NSString *) phoneNumberRef;
CFRelease(phoneNumberRef);
if ([phoneNumber rangeOfString:#"+"].location == NSNotFound) {
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#"." withString:#""];
self.lblMobileNumber.text = [NSString stringWithFormat:#"%#", phoneNumber];
} else {
NSArray *PhoneNumberComponents = [phoneNumber componentsSeparatedByString:#" "];
NSString * strCountryCode = PhoneNumberComponents[0] ;
[self.btnCountryCode setTitle:strCountryCode forState:UIControlStateNormal];
phoneNumber= [phoneNumber stringByReplacingOccurrencesOfString:PhoneNumberComponents[0] withString:#""];
NSLog(#"countryCodeSepratedStr%#",phoneNumber);
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#"." withString:#""];
self.lblMobileNumber.text = [NSString stringWithFormat:#"%#", phoneNumber];
}
}
}
}
return NO;
}
I wouldn't be inclined do any of that string manipulation stuff, but just use regular expression to look for + followed by number at start of the string, using capturing parentheses to grab just the country code:
NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"^\\s*\\+\\s*(\\d+)[^\\d]*(.*)$" options:0 error:&error];
NSTextCheckingResult *result = [regex firstMatchInString:phoneNumber options:0 range:NSMakeRange(0, [phoneNumber length])];
if (result) {
NSString *countryCode = [phoneNumber substringWithRange:[result rangeAtIndex:1]];
NSString *phoneNumberWithoutCountryCode = [phoneNumber substringWithRange:[result rangeAtIndex:2]];
} else {
// no country code found
}

UIKeyboardTypeDecimalPad detect if it has comma "," or dot "."

How can I check if the UIKeyboardTypeDecimalPad has a dot/comma? I need this to check how many dots/commas are entered so I can limit them to only 1. I know how to do this when I know that the UIKeyboardTypeDecimalPad has the comma.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *cs;
NSString *filtered;
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if ([textField.text rangeOfString:#","].location == NSNotFound) {
cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERSPERIOD] invertedSet];
filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
return [string isEqualToString:filtered];
}
else {
cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];
filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
NSUInteger count = 0, length = [newString length];
NSRange range = NSMakeRange(0, length);
while(range.location != NSNotFound)
{
range = [newString rangeOfString: #"," options:0 range:range];
if(range.location != NSNotFound)
{
range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
count++;
}
}
if (count < 2) {
NSArray *sep = [newString componentsSeparatedByString:#","];
if([sep count]>=2)
{
NSString *sepStr=[NSString stringWithFormat:#"%#",[sep objectAtIndex:1]];
return !([sepStr length]>2);
}
return YES;
}
return NO;
}
}
Is there easy way to check if the keyboard has the "," or "."?
I suspect the character on that key is governed by the current locale. I say I suspect because I have not tested this. If this is correct the following should allow you to determine whether a comma or period/decimal point is there:
NSString *symbol = [[NSLocale currentLocale] objectForKey:NSLocaleDecimalSeparator];

String with allowed chars

Is there a clean way to get a string containing only allowed characters?
for example:
NSString* myStr = #"a5&/Öñ33";
NSString* allowedChars = #"abcdefghijklmnopqrstuvwxyz0123456789";
NSString* result = [myStr stringWIthAllowedChrs:allowedChars];
result should now be #"a533";
It's not the cleanest, but you could separate the string using a character set, and then combine the resulting array using an empty string.
// Create a character set with every character not in allowedChars
NSCharacterSet *charSet = [[NSCharacterSet characterSetWithCharactersInString:allowedChars] invertedSet];
// Split the original string at any occurrence of those characters
NSArray *splitString = [myStr componentsSeparatedByCharactersInSet:charSet];
// Combine the result into a string
NSString *result = [splitString componentsJoinedByString:#""];
Simple and easy to customize and understand approach:
NSString* myStr = #"a5&/Öñ33";
NSString* allowedChars = #"abcdefghijklmnopqrstuvwxyz0123456789";
NSCharacterSet *set = [[NSCharacterSet characterSetWithCharactersInString:allowedChars] invertedSet];
NSString *result = myStr;
NSRange range = [result rangeOfCharacterFromSet:set];
while (range.location != NSNotFound)
{
result = [result stringByReplacingCharactersInRange:range withString:#""];
range = [result rangeOfCharacterFromSet:set];
}
NSLog(#"%#", result);
One of the simplest-
NSString* result = #"";
for(NSUInteger i = 0; i < [myStr length]; i++)
{
unichar charArr[1] = {[myStr characterAtIndex:i]};
NSString* charString = [NSString stringWithCharacters:charArr length:1];
if([allowedChars rangeOfString:charString].location != NSNotFound)
result = [result stringByAppendingString:charString];
}
return result;

Extract an NSString using NSScanner

I'm fetching data from AllContacts; in that data I'm getting contact details such as (998) 989-8989. Using this number, I'm not able to make a call. Can any one help out with this? Thanks in advance.
HI All
At last i have used this following code to resolve this issue
NSString *originalString = #"(998) 989-8989";
NSMutableString *strippedString = [NSMutableString
stringWithCapacity:originalString.length];
NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet
characterSetWithCharactersInString:#"0123456789"];
while ([scanner isAtEnd] == NO) {
NSString *buffer;
if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
[strippedString appendString:buffer];
} else {
[scanner setScanLocation:([scanner scanLocation] + 1)];
}
}
NSLog(#"%#", strippedString);
Thanks All
Sounds like you can just remove spaces, brackets and hypens.
NSString *phoneNumber = #"(998) 989-8989";
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
phoneNumber = [#"tel://" stringByAppendingString:phoneNumber];
[[UIApplication sharedApplication] openURL:phoneNumber];

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);