I am trying to create a javascript function capable of parsing a sentence and returning a number.
Here is jsFiddle I installed for test cases below -
- "I have 1 pound" β 1
- βI have Β£ 3.50 to spendβ β 3.50
- βI have 23.00 poundsβ β 23
- 'Β£ 27.33' β 27.33
- '$ 4345.85' β 4345.85
- '3.00' β 3
- '7.0' β 7
- 'Must have 2.0.' β 2
- "Must be 15.20." β 15.20
- '3.15' β 3.15
- "I have only 5, not very good." β 5
- '34.23' β 34.23
- 'sdfg545.14sdfg' β 545.14
- βYesterday I spent $ 235,468.13. Today I want to spend less. β 235468.13
- "Yesterday I spent 340pounds." β 340
- "Today I spent Β£ 14.52, tomorrow - Β£ 17.30" β 14.52
- "I have 0 trees, Β£ 11.33 tomorrow" β 0
16 and 17 indicate that he must find the first number. I understand that some of the test cases can be tough, but I welcome everything that gives me reasonable coverage.
Here is the format I use for my function
function parseSentenceForNumber(sentence){ return number;
I think I can get 60-80% of myself, but I expect that the correct expression may be the best solution here, and I have never been a great one. I hope I have enough test cases, but feel free to add any missing ones.
Your help is greatly appreciated.
** UPDATE **
Workloads of work answers, and I need to spend some time looking at them in more detail. Mike Samuel mentioned commas and .5, which forces me to add a couple more test cases
18. "I have 1000 pounds" β 1000 19. '5' β 0.5
And jsalonen mentioned adding a test case without numbers
20. 'This sentence contains no numbers' β null
Here is the updated fiddle using jsalonen solution, without my changes in the specification I would be 100% there, with the changes I am '95%. Can anyone suggest a solution to number 18 with commas?
** UPDATE **
I added an expression to split the commas into the jsalonen function, and I'm 100%.
Here is the final function
function parseSentenceForNumber(sentence){ var matches = sentence.replace(/,/g, '').match(/(\+|-)?((\d+(\.\d+)?)|(\.\d+))/); return matches && matches[0] || null; }
And the final fiddle
Really appreciate the help, and I improved my knowledge of regular expressions along the way. thanks