I'm trying to build a javascript function capable of parsing a sentence and returning a number.
Here is a jsFiddle I've setup for the 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
- 'Should have 2.0.' -> 2
- 'Should have 15.20.' -> 15.20
- '3.15' -> 3.15
- 'I only have 5, not great.' -> 5
- ' 34.23' -> 34.23
- 'sdfg545.14sdfg' -> 545.14
- 'Yesterday I spent £235468.13. Today I want to spend less.' -> 235468.13
- 'Yesterday I spent 340pounds.' -> 340
- 'I spent £14.52 today, £17.30 tomorrow' -> 14.52
- 'I have 0 trees, £11.33 tomorrow' -> 0
16&17 indicate that it should find the first number. I understand that some of the test cases may be tough but I welcome anything that gets me reasonable coverage.
Here is the format I'm using for my function
function parseSentenceForNumber(sentence){
return number; //The number from the string
}
I think I could get 60-80% of the way myself, but I expect a regular expression might be the best solution here and I've never been great at them. Hopefully I have enough test cases but feel free to add any I might of missed.
Your help is much appreciated.
**UPDATE**
Loads of working answers and I need to spend some time looking at them in more detail. Mike Samuel mentioned commas and .5 which leads me to add another couple of test cases
18.'I have 1,000 pound' -> 1000 19.'.5' -> 0.5
And jsalonen mentioned adding test case for no numbers
20.'This sentence contains no numbers' -> null
Here is the updated fiddle using jsalonen's solution, without my changes in spec I'd be 100% there, with the changes I'm 95%. Can anyone offer a solution to number 18 with commas?
**UPDATE**
I added a statement to strip out commas to jsalonen's function and I'm at 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 have improved my regular expression knowledge along the way. Thanks