iOS Regular Expression to check whether a NSString starts with g - ios

I am new to Regular Expressions and its usage in iOS .I have a scenario where I have to check whether a NSString starts with 'G' this is my function which returns the bool condition . I am passing the data like this
[self compareStringWithRegex:#"Gmail" withRegexPattern:#".*g"];
-(BOOL) compareStringWithRegex:(NSString *) string withRegexPattern:(NSString *)expression
{
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression options:NSRegularExpressionCaseInsensitive error:&error];
NSTextCheckingResult *match = [regex firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
if (match){
return YES;
}else{
return NO;
}
}
The problem I am facing is, this function returns true if I give wrong condition . Please help me in this and let me know if my question is not clear .

If you want to use Regular Expressions to check string start with "g" then
replace ".*g" with "^g" it will give you asspected result
[self compareStringWithRegex:#"Gmail" withRegexPattern:#"^g"];

If you really want to use regex the #"(g)+(\\w+)" should work. I tested it on Regex Tester

Related

In iOS how to check string against regular expression with boolean result

In iOS I need to check string against regular expression and if it passes then to return true (for example), if not false. I understand that I have to use NSRegularExpression class, but I can not figure out how.
You should read documentation.
Here is an example code how to do this in general:
- (BOOL)checkString:(NSString *)string {
NSString *const expression = #"^\\d{3}[-]\\d{2}[-]\\d{4}$"; // insert yours
NSError *error = nil;
NSRegularExpression * const regExpr =
[NSRegularExpression regularExpressionWithPattern:expression
options:NSRegularExpressionCaseInsensitive
error:&error];
NSTextCheckingResult * const matchResult = [regExpr firstMatchInString:string
options:0 range:NSMakeRange(0, [string length])];
return matchResult ? YES : NO;
}

Comparing using isEqualToString not working with Url encoded strings in iPhone

I am using flickrApi in iPhone. After authenticiation, i get their userId as
inNSID = (_NSCFString) #"108346178%40N06"
Note the %40
In my app, I am saving the same id in my server. At some other place, where i have to authenticate again, i use this id to check if authentication is already done or not., when i try to compare this string with my string using isEqualToString , the result is NO.
Here is log trace
Printing description of tempAcc->serviceId:
108346178%40N06
Printing description of inNSID:
108346178%40N06
Both seems to be exactly same, how can I compare both? What is going on here.
Use NSRegularexpression to scan Unicode strings for any matches.
NSString *string = #"108346178%40N06";
NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:string
options:NSRegularExpressionCaseInsensitive
error:&error];
NSTextCheckingResult *match = [regex firstMatchInString:string
options:NSMatchingReportCompletion
range:NSMakeRange(0, string.length)];
if (match) {
NSLog(#"yes");
} else {
NSLog(#"no");
}

Bold word of a sentence of NSString in Xcode

I have an issue in display sentence with a bold selected word.
NSString * string = #"Notes on iOS7 going to take a <-lot-> of getting used to!";
I want to print a sentence like this:
"Notes on iOS7 going to take a lot of getting used to!"
A plus that I have this code to select "lot" word. So how to base on this selected to bold the word. This string in this is example. So the range would be different.
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"(?<=<-).*?(?=->)"
options:0 error:&error];
if (regex) {
NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0))) {
NSString *result = [string substringWithRange:rangeOfFirstMatch];
NSLog(#"%#",result);
} else {
// Match attempt failed
}
} else {
// Syntax error in the regular expression
}
It will be:
Before: Notes on iOS7 going to take a <-lot-> of getting used to!
After: Notes on iOS7 going to take a lot of getting used to!
Thanks in advanced.
You have to use a NSAttributedString for that. Have a look at Any way to bold part of a NSString?

multiple ????'s in regex cause error

I have a simple regex search and replace method. Everything works fine as expected, however when I was hammer testing yesterday the string I entered had "????" in it. this caused the regex to fail with the following error...
error NSError * domain: #"NSCocoaErrorDomain" - code: 2048 0x0fd3e970
upon further research I believe that it might be treating the question marks as a "trigraph". Chuck has a good explanation in this post.What does the \? (backslash question mark) escape sequence mean?
I tried to escape the sequence prior to creating the regex with this
string = [string stringByReplacingOccurrencesOfString:#"\?\?" withString:#"\?\\?"];
and it seem to stop the error but the search and replace no longer works. Here is the method I am using.
- (NSString *)searchAndReplaceText:(NSString *)searchString withText:(NSString *)replacementString inString:(NSString *)text {
NSRegularExpression *regex = [self regularExpressionWithString:searchString];
NSRange range = [regex rangeOfFirstMatchInString:text options:0 range:NSMakeRange(0, text.length)];
NSString *newText = [regex stringByReplacingMatchesInString:text options:0 range:range withTemplate:replacementString];
return newText;
}
- (NSRegularExpression *)regularExpressionWithString:(NSString *)string {
NSError *error = NULL;
NSString *pattern = [NSString stringWithFormat:#"\\b%#\\b", string];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
if (error)
NSLog(#"Couldn't create regex with given string and options");
return regex;
}
My questions are; is there a better way of escaping this sequence? Is this a case of trigraphs, or another possibility? Or is a there a way in code of ignoring trigraphs or turning this off?
Thanks
My questions are; is there a better way of escaping this sequence?
Yes, you can properly escape any sequence of characters for a regular expression like this:
NSString* escapedExpression = [NSRegularExpression escapedPatternForString: aStringToEscapeCharactersIn];
EDIT
You don't have to run this on the whole expression. You can use NSString stringwithFormat: to insert escaped strings into REs with patterns in them e.g.
pattern = [NSString stringWithFormat: #"^%#(.*)", [NSRegularExpression escapedPatternForString: #"????"]];
will give you the pattern ^\?\?\?\?(.*)

NSRegularExpression, specify case-sensitive match?

Is there a way using NSRegularExpression to specify that you want to do a case-sensitive search? I am trying to match the upper-case TAG "ACL" in the text below. The pattern I am using is simply:
// Pattern
[A-Z]+
// SearchText
<td align=\"left\" nowrap><font face=\"courier, monospace\" size=\"-1\">ACL*</font></td>
// Code:
NSString *textBuffer = #"<td align=\"left\" nowrap><font face=\"courier, monospace\" size=\"-1\">ACL*</font></td>";
NSString *pattern = #"([A-Z]+)";
NSRegularExpression *regExp = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
NSTextCheckingResult *result = [regExp firstMatchInString:textBuffer options:0 range:NSMakeRange(0, [textBuffer length])];
NSLog(#"OBJECT CLASS: %#", [textBuffer substringWithRange:[result range]]);
Output: (with case-Insensative I am getting the first "td" as expected, when what I really want is "ACL"
I know that NSRegularExpressionCaseInsensitive is wrong, I was hoping there would be a NSRegularExpressionCaseSensitive. Also there is a flagOption ?(i) that also specifies a case-insensitive search but again nothing for case-sensative. What am I missing?
Case sensitive is the default. Dont put the insensitive flag in there.

Resources