ios - NSString regex for extracting negative numbers as part of an equation -
i'm trying match math equation using regex (in objective-c on iphone app), , utilize help in coming regex works sec scenario listed below.
i've created next objective-c code extract equation of form (1÷4) or (-1÷4) if there's negative number ahead of product or divider: (i include here help explain question i'm trying answer)
nsstring* equation = @"1+(-1÷4)"; nsstring* matcher = @"(-){0,1}(\\.|\\d)+(÷|×){1,}"; nsregularexpression *equation_regex = [nsregularexpression regularexpressionwithpattern:matcher options:nsregularexpressioncaseinsensitive error:nil]; while([equation_regex numberofmatchesinstring:working_function options:0 range:nsmakerange(0, [equation length])]) { // regex finds '-1÷4' } however, falls apart next equation: 3-1÷4 -1 shouldn't extracted since it's not part of 1÷4 in equation.
i've attempted alter regex (with limited regex expertise!) exlucde -1 iff there's number ahead of - via following:
nsstring* equation = @"3-1÷4"; nsstring* matcher = @"((^\\d)(-)){0,1}(\\.|\\d)+(÷|×){1,}"; nsregularexpression *power_regex = [nsregularexpression regularexpressionwithpattern:power_regex_pattern options:nsregularexpressioncaseinsensitive error:nil]; while([power_regex numberofmatchesinstring:working_function options:0 range:nsmakerange(0, [working_function length])]) { } where regex ((^\\d)(-)){0,1} effort match negative part if there's no leading digit on - (i.e. 1÷4 , not -1÷4), doesn't work, hence question. hope i've explained sufficiently! in advance.
if want avoid matching - if preceded digit, utilize
"((?<!\\d)-)?[\\d.]+[÷×][\\d.]+" the trailing ? in ((?<!\\d)-)? makes - optional, , if present, negative look-behind (?<!\\d) prevents match if preceded digit.
[\\d.]+ matches 0-9 or . 1 or more times.
note, tested using java.util.regex class, although think nsregularexpression class similar.
edit:
i find hard understand trying do, if trying match negative number if not preceded digit, use
"(?<!\\d)-\\d+(\\.\\d+)?" ios objective-c regex nsstring
No comments:
Post a Comment