Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

NSPredicate and Regexes



Hi All,

I am new to both cocoa and regex, so I would not be surprised to see that I just did a silly mistake in the regex in the following code:

NSString* regexFormat=@"[+-]?([0-9]*\.?[0-9]+)?[A-Z|a-z][A-Z|a-z| 0-9]*([+-]?([0-9]*\.?[0-9]+)?[A-Z|a-z][A-Z|a-z|0-9]*)*";
NSString* equation =@"X1+2X2+3X3";


NSPredicate* regexTest=[NSPredicate predicateWithFormat:@"SELF MATCHES %@",regexFormat];
if ([regexTest evaluateWithObject:equation] == YES) {
NSLog(@"Equation OK");

} else{
NSLog(@"Bad format for equation in Objective");
NSLog(equation);
}


I want to match any linear equation using the regex regexFormat. It works in most cases ( ie, it matches what I want and does not match what I don't), except that it does match X1+2X2++3X3, which is quite worrying. In addition to this, it does not match neither X1+2X2++X3 nor X1 +2X2++3.1X3.

I have done all the manipulations that came to my mind to check it and it looks like the presence of a integer ( and not floating) coefficient in front of a variable which is not the first one in the equation allows a double + in front of it. It also works with +- but does not work with more than two +.

Finally, I have tried it in python ( see code below ), and it does exactly what I want. Do you think there could be an issue with regexes using NSPredicate ?

Does anyone have a clue ?

Best regards,

rpechayr


Here the "equivalent" code in python :

#!/usr/bin/env python
# encoding: utf-8


import sys import os import re

def main():
reg ='[+-]?([0-9]*\.?[0-9]+)?[A-Z|a-z][A-Z|a-z|0-9]*([+-]?([0-9]*\.? [0-9]+)?[A-Z|a-z][A-Z|a-z|0-9]*)*'
prog=re.compile(reg)
result = prog.match('X1+2X2++1.00X3')
print result.group(0)

if __name__ == '__main__':
main()



_______________________________________________

Cocoa-dev mailing list (email@hidden)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/email@hidden

This email sent to email@hidden


Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.