views:

30

answers:

2

The last time I used a regular expression was 2 years ago and even then it wasn't something I considered to be the simplest of things!

Could anybody tell me how I would go about splitting this text into three groups (qty, name, price)?

  1 Corn Dog             5.00
  3 Corn Dog            15.00
    @ 5.00
  2 Diet Cola            4.00
    @ 2.00

I've attempted it myself following http://www.regular-expressions.info/reference.html but the symbols are getting overwhelming! I'm tempted to start doing some funky string manipulation as a plan B.

I'm using Objective-C so I'll probably use NSPredicate to execute the expression.

+1  A: 

A handy tool: Online RegEx Tester

I would start with ^\([:digit]+\)[:space:]*\(.*\)[:space:]\([:digit:]+\.[:digit:]{2}\)

Remember that different regex compilers have different rules about backslashing ()[]*+|

Bill Gribble
Note my regex wouldn't match the "@ 5.00" lines, but I assume they are just noise since the total price and quantity is on the lines that get matched, so you can compute the each price.
Bill Gribble
+1  A: 

I prefer this regex:

^\s*(\d+)\x09+([^\x09]+)\x09+\s*(.+)\s*$

You can refer to the capturing group as \1, \2, \3 if you refer to it the searching part of the regex, and you can refer to the capturing group as as $1, $2, $3 if you refer to it the replacing part of the regex.

However, my regex requires you to separate each field with one or more tab characters. I do this because separation with spaces could raise a disambiguity, so the regex would be longer.

Vantomex