NSRegularExpression string delimited by - objective-c

I have a string for example #"You've earned Commentator and 4 ##other$$ badges". I want to retreive the substring #"other", which is delimited by ## and $$. I made a NSRegularExpression like this:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"##(.*)$$" options:NSRegularExpressionCaseInsensitive error:nil];
This completely ignores $$ and returns stuff starting with ##. What am I doing wrong? thanks.

Thats because '$' is a special character that represents the end of the line. Try \$\$ to escape it and tell the parser you want the characters.

I wouldn't use a regex in this situation, since the string bashing is so simple. No need for the overhead of compiling the expression.
NSString *source = #"You've earned Commentator and 4 ##other$$ badges";
NSRange firstDelimiterRange = [source rangeOfString:#"##"];
NSRange secondDelimiterRange = [source rangeOfString:#"$$"];
NSString *result = [source substringWithRange:
NSMakeRange(firstDelimiterRange.origin +2,
firstDelimiterRange.origin - secondDelimiterRange.origin)];

Related

Apostrophes (') is not recognised in regular expression

I want a regular expression for first name that can contain
1)Alphabets
2)Spaces
3)Apostrophes
Exp: Raja, Raja reddy, Raja's,
I used this ^([a-z]+[,.]?[ ]?|[a-z]+[']?)+$ but it is failing to recognise Apostrophes (').
- (BOOL)validateFirstNameOrLastNameOrCity:(NSString *) inputCanditate {
NSString *firstNameRegex = #"^([a-z]+[,.]?[ ]?|[a-z]+[']?)+$";
NSPredicate *firstNamePredicate = [NSPredicate predicateWithFormat:#"SELF MATCHES[c] %#",firstNameRegex];
return [firstNamePredicate evaluateWithObject:inputCanditate];
}
May I recommand ^[A-Z][a-zA-Z ']* ?
// The NSRegularExpression class is currently only available in the Foundation framework of iOS 4
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"^[A-Z][a-zA-Z ']*" options:NSRegularExpressionAnchorsMatchLines error:&error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:searchText options:0 range:NSMakeRange(0, [string length])];
return numberOfMatches > 1;
^[A-Z] : Force start with a capital letter from A to Z
[a-zA-Z ']* : followed by any number of charactere that an be 'a' to 'z', 'A' to 'Z', space or simple quote
I think you are looking for a pattern like this: ^[a-zA-Z ']+$
However, this is pretty bad. What about umlauts, accents, and a whole lot other letters that are not part of the ASCII alphabet?
A better solution would be to allow any kind of letter from any language.
To do so you can use the Unicode "letter" category \p{L}, e.g. ^[\p{L}]+$.
.. or you could just drop that rule all together - as reasonably suggested.

Remove Special Characters, Numbers and Double Spaces from String

I want to remove Special Characters, Numbers and Double Spaces from a string, but it's removing all spaces. How can I fix it?
Code:
_tfName.text = [[_tfName.text componentsSeparatedByCharactersInSet:[[NSCharacterSet letterCharacterSet] invertedSet]] componentsJoinedByString:#""];
Strings:
Real String Formated What I want
___________ ________ ___________
Lincon Man LiconMan Licon Man
Name Surname NameSurname Name Surname
09123721*)(%!#ˆ*# *blank* *blank*
You have a lot of options available. A good one is to use NSRegularExpression for the two needs. One to find unwanted characters and remove them and another to find double spaces and remove them.
I recommend this option because you can reuse most of the logic for doing both.
You can also use NSScanner.
You could accomplish the unwanted characters part by using NSCharacterSet to create a set of chars you don't want and remove them with NSString method
– stringByTrimmingCharactersInSet:
that takes an NSCharacterSet argument.
NSString has
– stringByReplacingOccurrencesOfString:withString:
You can pass it a double space string.
Other options exist, but NSRegularExpression is the way to go for the double spaces.
The NSCharacterSet approach is pretty easy for the unwanted characters.
Did you think of passing a white space as the parameter to componentsJoinedByString:
string = [[string componentsSeparatedByCharactersInSet:[[NSCharacterSet letterCharacterSet] invertedSet]] componentsJoinedByString:#" "];
This may be what you are looking for:
NSRegularExpression *re = [NSRegularExpression regularExpressionWithPattern:#"[##$.,!\\d]" options:0 error:nil];
NSString *input = #"1234 Nöel* *Smith $!#";
NSString *output = [re stringByReplacingMatchesInString:input
options:0
range:NSMakeRange(0, [input length])
withTemplate:#""];
/* -> Nöel Smith */
Depending if you know what characters to remove or which ones to keep, you can write the regexp like this or the opposite with [^caracters-to-keep]. Just use the needed metacharacters for your case.

Objective C Regex?

I'm trying to parse a 7-digit number from a page's source code and the pattern that I look for is
/nnnnnnn"
where "n" is a digit. I'm trying with the following regex and in a regex test site it works, but not in obj-c. Is it possible that I'm passing the wrong option or something?
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"/\d\d\d\d\d\d\d\">" options:NSRegularExpressionSearch error:nil];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:contents
options:0
range:NSMakeRange(0, [contents length])];
You should double the backslashes in front of your ds, like this:
#"/\\d\\d\\d\\d\\d\\d\\d\">"
Backslash is a special character inside a string literal: the character after it is interpreted differently. In order for the regex engine to see a backslash, you need two slashes in the literal.

How to check if NSString contains a string with a specific format?

How can I detect if a certain NSString contains a string format like this for example:
I would like to check if a string is in a certain format. For example if I have the string format, #"%d %d/%d %#", I would like my code to return YES if I compare it against #"1 1/2 oz", and like wise would return NO if I compared it against #"20 ml".
What you want to use are regular expressions. The regex for this specific case is
[0-9]+\ [0-9]+\/[0-9]+\ [a-zA-Z]+
Try using NSRegularExpression.
Here's also a regex tutorial.
you can use NSRegularExpression
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:yourPattern options:NSRegularExpressionCaseInsensitive error:&error];

Objective C. Regular expression to eliminate anything after 3 dots

I wrote the following code to eliminate anything after 3 dots
currentItem.summary = #"I am just testing. I am ... the second part should be eliminated";
NSError * error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"(.)*(/././.)(.)*" options:0 error:&error];
if(nil != regex){
currentItem.summary = [regex stringByReplacingMatchesInString:currentItem.summary
options:0 range:NSMakeRange(0, [currentItem.summary length])
withTemplate:#"$1"];
}
However, my input and output are the same. The correct output should be "I am just testing. I am".
I was trying to do this using regular expression because I have a database of other regular expressions that I run on the string. I know the performance might not be as good as a plain text find or replace but the strings involved are short. I also tried using "\" to escape the dots in the regex, but I was getting a warning.
There is another question with a similar topic but the match strings are not for objective c.
This is much easier and will accomplish what you want:
NSRange range = [currentItem.summary rangeOfString:#"..."];
if (range != NSNotFound) {
currentItem.summary = [currentItem.summary substringToIndex:range.location];
}
You have forward slashes, /, instead of backward slashes, \, in your pattern. Also if you wish to match everything before the three dots you should use (.*) - tag everything matched by the enclosed .*. (The other parentheses in the pattern are redundant.)
Nice alternative:
NSScanner *scanner = [NSScanner scannerWithString:currentItem.summary];
[scanner scanUpToString:#"..." intoString: &currentItem.summary];
My recommended regex for your problem:
regularExpressionWithPattern:#"^(.*)\\s*\\.{3}.*$"
Main differences between this one and yours:
uses backslashes to escape special chars
uses ^ and $ to anchor at the beginning and end of the string
only captures the interesting section with ()
strips whitespace before the ... by ignoring any number of whitespace chars (\s*).
After correcting the slashes and other improvements, my final expression is:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"^(.*)\\.{3}.*$"
options:0
error:&error];