英文:
How to capture a stringified text "2,000.00" in bytes without the "," and convert it to float64?
问题
我的目标是在[]byte
中捕获一个字符串化的文本"2,000.00",并将其转换为float64
,问题是正则表达式捕获了带有","的MUTASI
组。
代码如下:
package main
import (
"bytes"
"fmt"
"regexp"
)
func main() {
mutasis := [][]byte{[]byte("28,000.00 DB"), []byte("5,000,000.00")}
re := regexp.MustCompile(`(?m)^(?P<MUTASI>[\d,.]+)(?: (?P<TIPE>DB|CR))*$`)
matches := re.FindAllSubmatch(bytes.Join(mutasis, []byte("\n")), -1)
for _, match := range matches {
fmt.Println(string(match[1]))
}
}
我所做的是:
- 使用
^(\d+(?:[,\d|.\d]+)*)$
,但显然,?:
被括号( )
覆盖了。
英文:
My goal is to capture a stringified text "2,000.00" in []byte
without the ,
and convert it to float64
. The problem is the regex captures Group MUTASI
with the ,
The code
package main
import (
"bytes"
"fmt"
"regexp"
)
func main() {
mutasis := [][]byte{[]byte("28,000.00 DB"), []byte("5,000,000.00")}
re := regexp.MustCompile(`(?m)^(?P<MUTASI>[\d,.]+)(?: (?P<TIPE>DB|CR))*$`)
matches := re.FindAllSubmatch(bytes.Join(mutasis, []byte("\n")), -1)
for _, match := range matches {
fmt.Println(string(match[1]))
}
}
What I've did:
- use
^(\d+(?:[,\d|.\d]+)*)$
but apparently,?:
is overriden by the brackets( )
.
答案1
得分: 3
尝试这个:
func toFloat(data []byte) (float, error) {
return strconv.ParseFloat(strings.ReplaceAll(string(data), ",", ""), 64)
}
将你的原始字节数组按空格分割,然后将其传递给这个函数。它将返回你需要的浮点数或错误。
英文:
Try this
func toFloat(data []byte) (float, error) {
return strconv.ParseFloat(strings.ReplaceAll(string(data), ",", ""), 64)
}
Split your original byte array by space, then pass it to this function. It will return either the float you need or error
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论