Regex Issue- can't get it to accept my expression - objective-c

I am running the following code, but my regex object is always nil and the error is telling me the regex is invalid (works fine in my regex tester!)
NSError *err = nil;
NSString *pattern = #"({{[^}]*}})";
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern: pattern
options: NSRegularExpressionCaseInsensitive
error: &err];
Do I need to escape anything in there? I tried adding \ before each curly brace, but that did not work either...

You need two backslashes as it is both the escape character for strings and for regular expressions, so \\ enters a single backslash into the string, and then the regular expression parser sees the backslash and escapes the brace: #"(\\{\\{[^}]*\\}\\})"

Related

How can I replace special characters by regex and Objective-C?

String: abc2_2fkf-lo
Now I want to use regex to delete the special characters as _ and -
The expect string as I want: abc22fkflo
Use stringByReplacingOccurrencesOfString.
NSString *string = #"abc2_2fkf-lo";
NSString *updated = [string stringByReplacingOccurrencesOfString:#"[-_]" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, string.length)];
This replaces any occurrence of a - or _ character with the empty string.
Note that if you want to match a - character using [ ] in a regular expression, the - needs to be the first character to avoid its normal special use as a character range operator.

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.

Objective-C: Parsing String into an Array under Special Circumstances

I have a string:
[{"id":1,"gameName":"arizona","cost":"0.5E1","email":"hi#gmail.com","requests":0},{"id":2,"gameName":"arizona","cost":"0.5E1","email":"hi#gmail.com","requests":0},{"id":3,"gameName":"arizona","cost":"0.5E1","email":"hi#gmail.com","requests":0}]
However, I would like to parse this string into an array such as:
[{"id":1,"gameName":"arizona","cost":"0.5E1","email":"hi#gmail.com","requests":0},
{"id":2,"gameName":"arizona","cost":"0.5E1","email":"hi#gmail.com","requests":0},
{"id":3,"gameName":"arizona","cost":"0.5E1","email":"hi#gmail.com","requests":0}]
This array is delimited by the comma in between the curly braces: },{
I tride usign the command
NSArray *responseArray = [response componentsSeparatedByString:#","];
but this separates the string into values at EVERY comma, which is not desirable.
Then I tried using regex:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\\{.*\\}" options:NSRegularExpressionCaseInsensitive error:&error];
NSArray *matches = [regex matchesInString:response options:0 range:NSMakeRange(0, [response length])];
which found one match: starting at the first curly brace to the last curly brace.
I was wondering if anyone new how to solve this problem efficiently?
This string seems to be valid JSON. Try a JSON parser: NSJSONSerialization
I agree with H2CO3's suggestion to use a parser where possible.
But looking at your attempted regex, it looks like you just need to make it non-greedy, i.e.
#"\\{.*?\\}"
^
|
Add this question mark for non-greedy matching.
Of course, this will fail if you have deeper levels of (what I assume to be) nested arrays. Go with the JSON parser!

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

(iOS) Error escaping a backslash in a string

I have a problem replacing a backslash in the string K90wuRcDX43cqDB7xkjReuzb\/nDaC0xc7Bqxi4Ft0T6EscKzEBXBJ6k8fFLl6j0S.
If I manually escape the backslash in the string I have no problem
NSString *mytoken = #"K90wuRcDX43cqDB7xkjReuzb\\/nDaC0xc7Bqxi4Ft0T6EscKzEBXBJ6k8fFLl6j0S";
NSLog(#"mytoken %#",mytoken);
mytoken K90wuRcDX43cqDB7xkjReuzb\/nDaC0xc7Bqxi4Ft0T6EscKzEBXBJ6k8fFLl6j0S
But if I try to do it programmatically then I can't escape the backslash (I tried with everything: CFString, stringByReplacingOccurrencesOfString, replaceOccurrencesOfString)
NSMutableString *mytokenOrig = [NSMutableString stringWithFormat:#"K90wuRcDX43cqDB7xkjReuzb\/nDaC0xc7Bqxi4Ft0T6EscKzEBXBJ6k8fFLl6j0S"];
[mytokenOrig replaceOccurrencesOfString:#"\\" withString:#"\\\\" options:NSCaseInsensitiveSearch range:(NSRange){0,[mytokenOrig length]}];
NSLog(#"mytokenOrig %#",mytokenOrig);
mytokenOrig K90wuRcDX43cqDB7xkjReuzb/
nDaC0xc7Bqxi4Ft0T6EscKzEBXBJ6k8fFLl6j0S
Note: I have to append this token to a string and calculate a hash, so it's so important to make it work.
That is because mytokenOrig doesn't contain a backslash, it already contains the escaped new-line.
[mytokenOrig replaceOccurrencesOfString:#"\n" withString:#"\\n" options:NSCaseInsensitiveSearch range:(NSRange){0,[mytokenOrig length]}];
However, you don't need to (re)escape a string. Escape characters are for you to be able to write special characters in code.