Sebastian Dwornik
Sebastian Dwornik

Reputation: 2576

How to use RegEx to support single line mode in textview?

I set my custom textview to support regExPatternValidation = @"^[0-9]{0,10}$";

and use the following method to accomplish my validation:

+ (BOOL)validateString:(NSString *)string withRegExPattern:(NSString *)regexPattern
{
    BOOL doesValidate = NO;
    NSError *error    = nil;

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexPattern
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];

    if (error)
    {
        DDLogError(@"%@:%@ : regular expression error: [%@]", THIS_FILE, THIS_METHOD, error.description);
        return doesValidate;
    }

    NSRange textRange = NSMakeRange(0, string.length);
    NSUInteger regExMatches = [regex numberOfMatchesInString:string options:NSMatchingReportCompletion range:textRange];

    if (regExMatches > 0 && regExMatches <= textRange.length+1)
    {
        doesValidate = YES;
    }
    else
    {
        doesValidate = NO;
    }

    return doesValidate;
}

One of its purposes is to control single or multi line modes. For some strange reason, when I hit the Return key (\n), the numberOfMatchesInString: still returns 1 match. Even though my regex pattern has no inclusion to support \n characters.

Is it possible to accomplish this feature using regex in Objective-C?

Upvotes: 0

Views: 127

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627126

The issue you have has its roots in how anchors ^ and $ work. ^ matches at the beginning (right before the first character, or \n in our case), and $ matches at the end of string (at \n). When you press Return, your string looks like \n. Exactly a match!

So, in your case [0-9]* can match an empty string due to the * quantifier (0 or more occurrences of the preceding pattern).

So, you can avoid matching an empty string with a negative look-ahead:

@"^(?!\n$)[0-9]*$"

It will not match an empty string with just a newline symbol in it. See this demo.

Upvotes: 1

Related Questions