Reputation: 171
I'm having troble breaking down a string into an array or matching patterns. here's the string:
Purchased:
12/7/11
58 - $2.5 Gold Coin @ $341.00
290 - Silver Dollar @ $36.02
Total - $500000.00
I want to parse this string and return an multi dimensional array like this:
Array
(
[0] => Array
(
[0] => 58 - $2.5 Gold Coin @ $341.00
[1] => 290 - Silver Coin @ $36.02
)
[1] => Array
(
[0] => 58
[1] => 290
)
[2] => Array
(
[0] => $2.5 Gold Coin
[1] => Silver Coin
)
[3] => Array
(
[0] => 341.00
[1] => 36.02
)
[4] => Array
(
[0] => .00
[1] => .02
)
)
so far I have this:
\s*?\n(\d*\.?\d*)\s-\s(.*?)\s\$(\d+(\.\d+)?\.?[0-9]*)
But the capturing groups are not working when there is a dollar sign in the product name (ie: '$2.5 Gold Coin')
I'm wondering if there is a way of only getting the amount from strings that start with '@ $'.
I've been using https://regex101.com/ to try and work it out which is an excellent tool but had no joy yet.
Upvotes: 0
Views: 144
Reputation: 626748
You may use
^(\d*\.?\d+)\s*-\s*(?:VF\s+)?(.*)\s@\s\$(\d+(\.\d+)?)
See the regex demo
Details
^
- start of a string(\d*\.?\d+)
- Group 1: 0+ digits, an optional .
and 1+ digits\s*-\s*
- -
enclosed with 0+ whitespaces(?:VF\s+)?
- an optional non-capturing group: VF
and 1+ whitespaces(.*)
- Group 2: any 0+ chars other than line break chars as many as possible\s@\s
- a @
enclosed with 1 whitespace\$
- a $
char(\d+(\.\d+)?)
- Group 3: 1 or more digits followed with an optional group 4 matching a dot and then 1+ digits.Upvotes: 1