Skip navigation.
 
mlNSPredicate and Regexes
FROM : Romain Pechayre
DATE : Sun Mar 30 12:26:48 2008

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()

Related mailsAuthorDate
mlNSPredicate and Regexes Romain Pechayre Mar 30, 12:26
mlRe: NSPredicate and Regexes Keary Suska Mar 30, 17:48