Regular Expression in Objective-C - iphone

I want to replace all tags which are like <xxxx>.
I tried this:
- (NSString *)grabData:(NSString *)searchTerm {
// Setup an error to catch stuff in
NSError *error = NULL;
//Create the regular expression to match against
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"<.*>" options:NSRegularExpressionCaseInsensitive error:&error];
// create the new string by replacing the matching of the regex pattern with the template pattern(whitespace)
NSString *newSearchString = [regex stringByReplacingMatchesInString:searchTerm options:0 range:NSMakeRange(0, [searchTerm length]) withTemplate:#""];
NSLog(#"New string: %#",newSearchString);
return newSearchString;
}
But this just doesn't work. Could anyone help me?

The pattern <.*> matches a less-than, any amount of anything including a greater than, and then a greater-than. This pattern would, for instance, match a complete HTML file...
What you need is a <[^>]+> the [^>] is the set of all characters excluding greater-than, the + is "one or more", so the whole thing matches a less-than, one or more of anything excluding a greater than, and then a greater-than.

Your regular expression is incorrect.
< and > are meta characters and need escaping
The pattern matching should be .+
Based on this use
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\\<.+\\>" options:NSRegularExpressionCaseInsensitive error:&error];
and it should work

Related

How can I find a dynamic number in a long NSString?

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.

Problem with regex detecting $<name>

I am trying to detect the following expression: $
for example
$john
or
$mike
What is wrong with my regex?
//Check for $symbol
NSRegularExpression *symbolRegex = [[NSRegularExpression alloc] initWithPattern:#"($[a-zA-Z0-9_]+)"
options:NSRegularExpressionCaseInsensitive
error:nil];
matches = [symbolRegex matchesInString:labelText options:0 range:NSMakeRange(0, [labelText length])];
for (NSTextCheckingResult *result in matches) {
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"symbol://%#",[labelText substringWithRange:result.range]]];
[bodyLabel addCustomLink:url inRange:[result range]];
}
[symbolRegex release];
It looks like you need to escape the $.
(\\$[a-zA-Z0-9_]+)
$ (dollar)
Matches at the end of the string the regex pattern is applied to.
Matches a position rather than a character. Most regex flavors have an
option to make the dollar match before line breaks (i.e. at the end of
a line in a file) as well. Also matches before the very last line
break if the string ends with a line break.
Since it's a special/reserved character, it needs to be escaped.
http://www.regular-expressions.info/reference.html

iPhone: regular expression and text input validation in UITextField is failing

I have the following code thats supposed to take the input entered into a UITextField and validate it. It doesn't seem to be working and Im a little confused as to why.
Could someone give me some advice please?
NSString *const regularExpression = #"([0-9a-zA-Z\\s]{1,6})";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regularExpression options:NSRegularExpressionCaseInsensitive error:&error];
if (error)
{
NSLog(#"error %#", error);
}
NSUInteger numberOfMatches =
[regex numberOfMatchesInString:s options:0 range:NSMakeRange(0, [s length])];
NSLog(#"index = %d", i);
NSLog(#"Value of TextField = %#", s);
NSLog(#"Regular expression is = %#", regularExpression);
if (numberOfMatches <= 0)
{
NSLog(#"Failed regex test ");
}
This string should fail the regular expression test :"Einxnkxkd Xnckck"
But it passed.
im not sure how and why...
Anything obvious Im missing here?
Thanks
The method numberOfMatchesInString: searches for matches within the string. It does not test your pattern against the entire string.
It is passing because the pattern ([0-9a-zA-Z\\s]{1,6}) is matching at least the first six letters of your test string Einxnkxkd Xnckck yielding Einxnk. In fact, I can find lots of matches: E, Ein, inx, etc.
If you want to make sure the whole string matches the pattern, use ^ to indicate the beginning of the string and $ to mark the end of it, so that your pattern becomes ^([0-9a-zA-Z\\s]{1,6})$.
If you want to limit the expression to exactly the string, you need to wrap the expression in ^..$:
NSString *const regularExpression = #"^([0-9a-zA-Z\\s]{1,6})$";
Edit: Use the RegEx Air app to test, it's pretty handy (or any other reg exp tester)

How to check if a string contains English letters (A-Z)?

How can I check whether a string contains the English Letters (A through Z) in Objective-C?
In PHP, there is preg_match method for that.
One approach would be to use regular expressions — the NSRegularExpression class. The following demonstrates how you could detect any English letters, but the pattern could be modified to match only if the entire string consists of such letters. Something like ^[a-zA-Z]*$.
NSRegularExpression *regex = [[[NSRegularExpression alloc]
initWithPattern:#"[a-zA-Z]" options:0 error:NULL] autorelease];
// Assuming you have some NSString `myString`.
NSUInteger matches = [regex numberOfMatchesInString:myString options:0
range:NSMakeRange(0, [myString length])];
if (matches > 0) {
// `myString` contains at least one English letter.
}
Alternatively, you could construct an NSCharacterSet containing the characters you're interested in and use NSString's rangeOfCharacterFromSet: to find the first occurrence of any one. I should note that this method only finds the first such character in the string. Maybe not what you're after.
Finally, I feel like you could do something with encodings, but haven't given this much thought. Perhaps determine if the string could be represented using ASCII (using canBeConvertedToEncoding:) and then check for numbers/symbols?
Oh, and you could always iterate over the string and check each character! :)
You can use simple NSPredicate test.
NSString *str = #"APPLE";
NSString *regex = #"[A-Z]+";
NSPredicate *test = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", regex];
BOOL result = [test evaluateWithObject:str];
You could also use NSCharacterSet and use the rangeOfCharacterFromSet: method to see if the returned NSRange is the entire range of the string. characterSetWithRange would be a good place to start to create your characterSet.
You can use the NSRegularExpression Class (Apple's documentation on the class can be viewed here)

what's the best way to detect if a word in NSString has a number?

example: word with number in string
NSString *str = [NSString stringWithFormat:#"this is an 101 example1 string"]
Since example1 has a number in the end and i want to remove it. I can break it into an array and filter it out using predicate, but that seems slow to me since I need to do like a million of these.
What would be a more efficient way?
Thanks!
Probably NSRegularExpression. I think ([^0-9 ]+)\d+|\d+([^0-9 ]+) should do it. Just replace it with $1.
Based on Chuck's response, here is the complete code in case someone might find it useful:
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"([^0-9 ]+)\\d+|\\d+([^0-9 ]+)"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:str2
options:0
range:NSMakeRange(0, [str2 length])
withTemplate:#"$1"];