How to capture a stringified text "2,000.00" in bytes without the "," and convert it to float64?

huangapple go评论71阅读模式
英文:

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]))
	}
}

我所做的是:

  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 (
	&quot;bytes&quot;
	&quot;fmt&quot;
	&quot;regexp&quot;
)

func main() {
	mutasis := [][]byte{[]byte(&quot;28,000.00 DB&quot;), []byte(&quot;5,000,000.00&quot;)}
	re := regexp.MustCompile(`(?m)^(?P&lt;MUTASI&gt;[\d,.]+)(?: (?P&lt;TIPE&gt;DB|CR))*$`)
	matches := re.FindAllSubmatch(bytes.Join(mutasis, []byte(&quot;\n&quot;)), -1)
	for _, match := range matches {
		fmt.Println(string(match[1]))
	}
}

What I've did:

  1. 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), &quot;,&quot;, &quot;&quot;), 64)
}

Split your original byte array by space, then pass it to this function. It will return either the float you need or error

huangapple
  • 本文由 发表于 2022年9月1日 00:07:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/73558835.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定