How can I parse a string to extract numbers using a regular expression using NSRegularExpression?

I am new to regular expressions and have no idea how to work with them. I wanted to create a regex for the following piece of text to get the min, average and max times. I would use them with NSRegularExpression to get a range and then a string.

Can someone please help in creating a regex for the text below.

round-trip min/avg/max/stddev = 3.073/6.010/13.312/2.789 ms

      

+3


source to share


3 answers


Break it down.

I am assuming that you want to get the numeric values ​​from this string and toss the rest.

First, make a regex to match the number:

  • \d

    corresponds to the figure
  • \d*

    matches zero or more digits
  • \.

    corresponds to the period
  • (\d*\.\d*)

    matches zero or more digits, then a period, then zero or more digits

Then turn it into a Cocoa string:

  • @"(\\d*\\.\\d*)"

Then do NSRegularExpression

:

NSError error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\\d*\\.\\d*)"
    options:NSRegularExpressionCaseInsensitive
    error:&error];

      

Then get an array with all matches:



NSArray *matches = [regex matchesInString:string
                              options:0
                                range:NSMakeRange(0, [string length])];

      

Then pull out the values:

NSString* minText = [string substringWithRange:[matches[0] range]];
NSString* avgText = [string substringWithRange:[matches[1] range]];
// etc.

      

I leave this as an exercise to convert these strings to floats. :-)


Update: I found myself so honed with the complexity of this that I created a little library, humbly calling Unsuck , that adds some sanity to NSRegularExpression

in the form of methods from

and allMatches

. This is how you use them:

NSRegularExpression *number = [NSRegularExpression from: @"(\\d*\\.\\d*)"];
NSArray *matches = [number allMatches:@"3.14/1.23/299.992"];

      

Please check the source code on github and tell me everything I did wrong :-)

+8


source


I know you want a regex and they are very easy to learn, but it might be a little harder than it needs to be for this situation. With this in mind, I provide an alternative. I'm sure someone else will give you a regex.



NSString* str = @"round-trip min/avg/max/stddev = 3.073/6.010/13.312/2.789 ms";

NSString* str2 = [str substringFromIndex:32];

NSArray* components = [str2 componentsSeparatedByString:@"/"];

CGFloat min = [[components objectAtIndex:0] doubleValue];
CGFloat avg = [[components objectAtIndex:1] doubleValue];
CGFloat max = [[components objectAtIndex:2] doubleValue];

NSLog(@"min/avg/max: %f/%f/%f",min,avg,max);

      

+1


source


I managed it using (.*) = (.+?)/(.+?)/(.+?)/(.*)

0


source







All Articles