Reputation: 27852
I have input lines like this:
1 soccer ball at 10
2 Iphones 4s at 199.99
4 box of candy at 50
And I want to get the first digit, the item itself and the price (I don't want the "at").
I have done the following regex:
/^(\d+)\sat\s(\d+\.?\d*)$/
But as you can see I am missing what comes before the "at". What should I put there?
Upvotes: 1
Views: 51
Reputation: 12985
Here's my version:
// double escaped \ as it's supposed to be in PHP
'~(\\d+)\\s+(.+?)\\s+at\\s+(\\d+(?:,\\d+)?(?:\\.\\d+)?)~'
// catches thousands too but stays strict about the order of , and .
Cheers!
PS: Might fail for products that codes over 1 million of bucks :)
Upvotes: 1
Reputation: 1830
Here you have (\d+)\s([\w ]+)\sat\s(\d+(?:\.\d+)?)
As you can see in the demo, the explanation
/(\d+)\s([\w ]+)\sat\s(\d+(?:\.\d+)?)/g
1st Capturing group (\d+)
\d infinite to 1 times. Digit [0-9]
\s Whitespace [\t \r\n\f]
2nd Capturing group ([\w ]+)
Char class [\w ] infinite to 1 times. matches one of the following chars: \w
\w Word character [a-zA-Z_\d]
\s Whitespace [\t \r\n\f]
at Literal `at`
\s Whitespace [\t \r\n\f]
3rd Capturing group (\d+(?:\.\d+)?)
\d infinite to 1 times. Digit [0-9]
Group (?:\.\d+) 1 to 0 times.
\. Literal `.`
\d infinite to 1 times. Digit [0-9]
g modifier: global. All matches (don't return on first match)
Upvotes: 0