Portal Home > Knowledgebase > Articles Database > regular expression help


regular expression help




Posted by larwilliams, 05-31-2009, 02:14 PM
Hi, I am making a small currency conversion system for a friend and need some basic regular expression help. I need to be able to parse out the currency names and rates from a string that will always follow the same format The format is as follows: 1 CAD = USD (0.912324) I need to be able to get the four pieces of information 1) amount in base currency (in this case, CAD) 2) base currency name (in this case, CAD) 3) converted currency name (in this case, USD) 4) conversion rate (in this case, 0.912324) My regexp skills are a bit rusty, so any assistance would be appreciated.

Posted by Steve_Arm, 05-31-2009, 02:35 PM
Of course, or for last part without the parentheses Last edited by Steve_Arm; 05-31-2009 at 02:42 PM.

Posted by larwilliams, 05-31-2009, 02:49 PM
Thanks, I just cooked my own solution in the mean time and come up with something a bit more generic than yours

Posted by mwatkins, 05-31-2009, 04:54 PM
On a sunny Vancouver afternoon I'm a bit too lazy to delve into the PHP docs to build an equivalent approach to the following no-regex solution, so I'll just throw out this Python example just in case there is value in translating it to PHP. I like regexes more than most but sometimes avoiding them is a nice thing. Assume you are populating "line" with a foreach looping through the input data - splitting the line on the whitespace gives you: And here's a full solution for decoding one line. It's a little longer because I am casting the values (which a regex still returns to you as a string) to usable values in the right type (for base_amount and rate): What are those variables containing now?

Posted by mwatkins, 05-31-2009, 05:04 PM
The other, probably more likely, approach I would take is to use our trusty regex tool to do the splitting: This gets us almost all the way there: This gets us closer yet: Putting it all together: PHP has preg_split, worth a look perhaps. http://ca3.php.net/manual/en/function.preg-split.php

Posted by Cmafai, 06-01-2009, 07:13 PM
If you want to be lazy, and the regex is bugging you for some reason, an alternative would be to simply use a function like substr() to get each part. Of course that is completely pointless and stupid if the format is going to change at all. I really don't recommend this approach unless something weird is preventing you from using one of the other solutions. Just thought I'd throw in an alternative



Was this answer helpful?

Add to Favourites Add to Favourites    Print this Article Print this Article

Also Read
APF to block an IP (Views: 773)


Language:

LoadingRetrieving latest tweet...

Back to Top Copyright © 2018 DC International LLC. - All Rights Reserved.