92: Fix ParseCoins regexp in general
This commit is contained in:
+10
-6
@@ -20,22 +20,26 @@ func (coin Coin) String() string {
|
||||
}
|
||||
|
||||
//regex codes for extracting coins from string
|
||||
var reDenom = regexp.MustCompile("([^\\d\\W]+)")
|
||||
var reDenom = regexp.MustCompile("")
|
||||
var reAmt = regexp.MustCompile("(\\d+)")
|
||||
|
||||
var reCoin = regexp.MustCompile("^([[:digit:]]+)[[:space:]]*([[:alpha:]]+)$")
|
||||
|
||||
func ParseCoin(str string) (Coin, error) {
|
||||
var coin Coin
|
||||
|
||||
if len(str) == 0 {
|
||||
return coin, errors.New("Empty string is invalid coin")
|
||||
matches := reCoin.FindStringSubmatch(strings.TrimSpace(str))
|
||||
if matches == nil {
|
||||
return coin, errors.Errorf("%s is invalid coin definition", str)
|
||||
}
|
||||
|
||||
amt, err := strconv.Atoi(reAmt.FindString(str))
|
||||
// parse the amount (should always parse properly)
|
||||
amt, err := strconv.Atoi(matches[1])
|
||||
if err != nil {
|
||||
return coin, err
|
||||
}
|
||||
denom := reDenom.FindString(str)
|
||||
coin = Coin{denom, int64(amt)}
|
||||
|
||||
coin = Coin{matches[2], int64(amt)}
|
||||
return coin, nil
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -67,6 +67,7 @@ func TestParse(t *testing.T) {
|
||||
{"10bar", true, Coins{{"bar", 10}}},
|
||||
{"99bar,1foo", true, Coins{{"bar", 99}, {"foo", 1}}},
|
||||
{"98 bar , 1 foo ", true, Coins{{"bar", 98}, {"foo", 1}}},
|
||||
{" 55\t \t bling\n", true, Coins{{"bling", 55}}},
|
||||
{"2foo, 97 bar", true, Coins{{"bar", 97}, {"foo", 2}}},
|
||||
{"5 mycoin,", false, nil}, // no empty coins in a list
|
||||
{"2 3foo, 97 bar", false, nil}, // 3foo is invalid coin name
|
||||
@@ -78,7 +79,7 @@ func TestParse(t *testing.T) {
|
||||
for _, tc := range cases {
|
||||
res, err := ParseCoins(tc.input)
|
||||
if !tc.valid {
|
||||
assert.NotNil(err, tc.input)
|
||||
assert.NotNil(err, "%s: %#v", tc.input, res)
|
||||
} else if assert.Nil(err, "%s: %+v", tc.input, err) {
|
||||
assert.Equal(tc.expected, res)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user