Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective c - sentence validation regex

In Objective-c, I want to check is a proper english sentence/word or not, not grammatically.. i.e: texts like "I didn't go!", ""Hi" is a word", "hello world", "a 5 digit number", "the % is high!" and "[email protected]" should pass. but texts like "@/-5%;l:" should NOT pass the text may contain: numbers 0-9 and letters a-z, A-Z and -/:;()$&\"'!?,._

I tried:

NSString *regex1 = @"^[\w:;()'\"\s-]*";
NSPredicate *streamTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex1];
return [streamTest evaluateWithObject:candidate];

But it wouldn't achieve what I want Any ideas?

like image 523
mim Avatar asked May 01 '26 01:05

mim


1 Answers

I agree with @borrrden that this is a difficult task for a regex, but one thing you'd need to do is to escape the regex-backslashes (for want of a better word) with another backslash (\). Like this:

NSString *regex1 = @"^[\\w:;()'\"\\s-]*";

The reasoning behind this is that you want the regex engine to "see" the backslash, but the compiler which handles the NSString also uses backslashes to escape certain characters. "w" and "s" are not among those characters, so they \w and \s are just translated into w and s, respectively.

A double backslash in a literal string serves to get a single backslash into the compiled string.

like image 131
Monolo Avatar answered May 02 '26 16:05

Monolo