How to avoid the hyphen entered in the textfield using regular expressions? - iphone

I have a textfield where I am performing validations using regular expressions. But I have a problem when the user enters hyphen in the textfield and click on the button then an alert should be provided that no entered is not valid. I am performing validations for string and special characters but for special characters it is not getting validated.
This is my code:
NSRegularExpression *regex = [[[NSRegularExpression alloc]
initWithPattern:#"[a-zA-Z][#$%&*()']" options:0 error:NULL] autorelease];

You can check occurance of hyphen using rangeOfString
NSRange k = [str rangeOfString:#"-"];
if(k.length != 0)
... Show your alert message
I feel this will meet your requirements, No need to step in complexity if regexp..

I'm not very familiar with objective-c and it's flavor of regular expressions, and I'm not completely clear on what you are asking, but your regular expression will not match a hyphen. It should match a letter followed by one of the following characters: #$%&*()'. Below are a few examples of what should match and some things that should not match:
SHOULD MATCH SHOULD NOT MATCH
---- ---- ---- ------ ------
a# a$ A -- C3PO
A) A* # - huh?
T% Q# g- AA## 123
j& a( $R () bbb5
z' B& qq "D%" ()-
If any of these are inconsistent with what you want to match, then you need to ask a question containing the desired pattern that you want to match. Some examples would be:
"any number of letters, parentheses, asterisks, ampersands"
"any number of any character except hyphens and square brackets ([])"
"between one and three capital letters followed by an optional number"
...or whatever meets your requirements.
Regular Expressions are a language that allows specification of almost any pattern of text-based data. If you do not need to match a pattern, then regular expressions might not be necessary. Good luck!

Don't show an alert because a user entered a character you don't like. That's terrible UX, especially when using a soft keyboard where typos are more likely.
Instead, process the input to extract the characters you do want. Think of a writing a web form with an input field for a phone number. You're not interested in the human-readable formatting in the phone number--the hyphens, the plus prefix to the country code, etc. But nothing should stop the user from entering those characters. You have code that can strip out the invalid characters leaving what you want.
NSString even makes this easy for you with -stringByTrimmingCharactersInSet:. You define an NSCharacterSet with the characters you want removed from a given NSString instance, invoke -stringByTrimmingCharactersInSet:, and you get an autoreleased NSString instance with only the characters you want in it, e.g.:
NSString *rawInput; // value assigned elsewhere to #"555-555-1212"
NSCharacterSet *characterSet = [ NSCharacterSet characterSetWithCharactersInString: #"-" ];
NSString *processedInput = nil;
processedInput = [ rawInput stringByTrimmingCharactersInSet: characterSet ];
NSLog( #"processedInput: %#", processedInput ); // logs "5555551212"

Related

In search of Regular Expression to return substring of Phone number

I've looking looking at this with no success so far. I need a regular expression that returns me the string after the one in a phone number. Let me give you the perfect example:
phone number (in exact format i need): 15063217711
return i need: 5063217711 --> so the FIRST char if its a 1 is removed. I need a regular expression that matches a 1 only at the BEGINNING of the string and then returns the rest of the phone number.
By the way im using objective C but it should not make much difference.
Use positive lookbehind to skip digit 1: (?<=^1)\d+$
There's really no need for a regular expression.
Just test if the first character in the string is a 1 and if so, take the substring of the rest.
Check out [NSString characterAtIndex:] and [NSString substringFromIndex:]

Convert first Letter of each word of a sentence to capital in iPhone

I have the string:
i am a bad boy.
I want to convert that string into:
I Am A Bad Boy.
What I have tried only has worked for the first character of a word.
Here is Solution:
NSString *str=#"i am a bad Boy";
str=[str capitalizedString];
NSLog(str);
output will be:
I Am A Bad Boy.
use- capitalizedString method.
This method returns:
A string with the first character from each word in the receiver
changed to its corresponding uppercase value, and all remaining
characters set to their corresponding lowercase values.
You can check NSString documentation for more details -
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html

How can I use regex to put quotes around a statement

I am using regexkitlite to validate some data in my iPhone app in xcode.
I am making an api call that sends a json result of:
"taskDate": newDate("September 23, 2011 00:00:00")
how do i use regex to convert it to:
"taskDate": "newDate("September 23, 2011 00:00:00")"
I want to surround the value of every "taskdate" key with quotes.
Edit: Adding OP's comment
Here is what i am using:
[resultString replaceOccurrencesOfRegex:#"new Date((.*?)\")," withString:#"\"\"," range:NSMakeRange(0, [resultString length])];
where resultString is the string containing the "new Date(...."
You can use regex to identify where in your text you have text in the format of "taskDate": "newDate("September 23, 2011 00:00:00")" but the actual replacement you will have to write yourself. Regex doesn't replace strings, it finds patterns within a string. Now, in order to find the pattern of "taskDate": newDate("<anything can go here>") you can use
"taskDate"\: newDate\(".*?"\)
If it is possible to have something else within the parenthesis, you will have to be more specific and only specify a date inside:
"taskDate"\: newDate\("[a-zA-z]* \d{2}, \d{4} \d{2}\:\d{2}\:\d{2}"\)
This will match everything of the sort of "taskDate"\: newDate\("Letters 00, 00:00:00"\). From here you can either make the months specific, and allow white space between all the quotations. All these changes makes the regex more complex, so only make it more strict to avoid matching things that you don't want. If no scenario exist that something else can be inside the parenthesis, I would go with the first regex.
That said, after you match the string within your content, you need to write the code to surround it with the quotations.

removing a specific string from a string and the next string after a space

i have a string #"ABC 1.23 bla bla bla" from which i have to remove the #"ABC" string and after that the string #"1.23". The problem is that the text #"1.23" varies .. it could be #"1.55" etc. How can i remove the string #"ABC" and the next word after space ?
You can use regular expressions, or you can do that in several ways using NSString methods.
use componentsSeparatedByString and pass a space; your string will be split in an array at word boundaries; then you use componentsJoinedByString: ignoring the first two elements of the array;
you can use twice in succession rangeOfString: passing a space in; the first time it will find the space after ABC; the second time, it will find the space after 1.23 (or whatever); then you get the substringFromIndex: starting at that position.
Regular expression would give you much more options, but it would be a steeper curve, if you have never used regex in ObjC. Have a look at RegExKitLite if you are interested.

How to extract certain text with NSRegularExpression?

I'm trying to extract (80.4) from the following code:
<div id="row" style="width:80.4px">
What would the expression look like to extract that text? Thanks.
A regex is rather heavyweight for this particular situation. I would just do this:
NSString *originalString; //which will contain "<div id="row" style="width:80.4px">", however you want to get it there
NSString *afterColon = [[originalString componentsSeparatedByString:#":"] objectAtIndex:1];
float theValue = [afterColon floatValue];
Here are two possibilities but the answer will vary depending on the following factors:
1) what other content is in the text that you do NOT want to match against,
2) and what variations will you permit to match against (eg. adding spaces or new lines inside the test that you want to match, or swapping the order of the parts of the text to match)
This matches only the "width:80.4px" portion of your given string (allowing for extra white space):
width\s*:\s*(\d+.\d+)\s*px
And this matches the entire string that you gave (also allowing for extra white space):
<div\s+id\s*=\s*"row"\s+style\s*=\s*"width:\s*(\d+.\d+)\s*px">
So in these regexs the 80.4 will be captured in the $1 capture group.