Frage

I'm actually totally lost trying to use a regex into a NSpredicate. What i want is a regex who find all the beginning of words in a sentence who match criteria. The fact is that doesn't work.

Here's my regex: .*\b xxx [\w-]* (where xxx is my criteria).

And here's the code

   NSString* regexString   = [NSString stringWithFormat: @".*\\b%@[\\w-]*", search];
   request.predicate       = [NSPredicate predicateWithFormat:@"adresse matches[cd] %@", regexString];

adress are a string property of my core data object. But for some obscure reason, that doesn't work. Can someone help me?

For example: CITY SANDWITCH 67200 STRASBOURG

.*\bStra[\w-]* will find STRASBOURG

but .*\b672[\w-]* or .*\bSAND[\w-]* will result nothing.

edit

I finally give up and wrote (adresse BEGINSWITH[c] %@) OR (adresse CONTAINS[c] %@) statement instead, where %@ is the search word term.

But the topic is still open if someone can explain me why simple regex formula in obj-c seems like lauching a rocket in space. What is strange is the regex actually works, but half the way it should be, like if the rule wasn't strictly followed. I'm really confused now.

War es hilfreich?

Lösung

I didn't use the same object as you did but another that I understand a bit more and that looks more like Java's one ;)

NSString* string = @"CITY SANDWITCH 67200 STRASBOURG";
NSString* search = @"SAND"; // work also with 672 or STRAS
NSString* regexString  = [NSString stringWithFormat: @".*\\b(%@[\\w]*)[\\s*\\w*]*", search];
NSError  *error  = NULL;

NSRegularExpression *regex = [NSRegularExpression
                              regularExpressionWithPattern:regexString
                              options:0
                              error:&error];

NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@"$1"];

NSLog(@"-->%@", modifiedString);

Andere Tipps

Try changing regexString to

NSString* regexString   = [NSString stringWithFormat: @".*\\b%@.*", search];
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top