Return a defined range of characters in Go

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

Return a defined range of characters in Go

问题

让我们假设我们有一个转换为字符串的浮点数:

"24.22334455667"

我想只返回小数点右边的6位数字。

我可以通过以下方式获取小数点后的所有数字:

re2 := regexp.MustCompile(`[!.]([\d]+)$`)

但是我只想要小数点后的前6位数字,但是这样返回的是空的:

re2 := regexp.MustCompile(`[!.]([\d]{1,6})$`)

我该如何做到这一点?我找不到使用[\d]{1,6}的示例。

谢谢

英文:

Let's say we have a converted float to a string:

"24.22334455667"

I want to just return 6 of the digits on the right of the decimal

I can get all digits, after the decimal this way:

re2 := regexp.MustCompile(`[!.]([\d]+)$`)

But I want only the first 6 digits after the decimal but this returns nothing:

re2 := regexp.MustCompile(`[!.]([\d]{1,6})$`)

How can I do this? I could not find an example of using [\d]{1,6}

Thanks

答案1

得分: 4

另外...

func DecimalPlaces(decimalStr string, places int) string {
    location := strings.Index(decimalStr, ".")
    if location == -1 {
        return ""
    }
    return decimalStr[location+1 : min(location+1+places, len(decimalStr))]
}

其中min是一个简单的函数,用于找到两个整数的最小值。

对于这种简单的字符串操作,正则表达式似乎有点过重。

Playground

英文:

Alternatively...

func DecimalPlaces(decimalStr string, places int) string {
	location := strings.Index(decimalStr, ".")
	if location == -1 {
		return ""
	}
	return decimalStr[location+1 : min(location+1+places, len(decimalStr))]
}

Where min is just a simple function to find the minimum of two integers.

Regular expressions seem a bit heavyweight for this sort of simple string manipulation.

Playground

答案2

得分: 3

你必须移除行尾锚点$,因为在恰好6个数字之后它不会是行尾。要捕获恰好6个数字,量词应该是

re2 := regexp.MustCompile(`[!.](\d{6})`)

请注意,这也会匹配!后面的数字。如果你不想要这种行为,你必须从字符类中移除!,像这样

re2 := regexp.MustCompile(`[.](\d{6})`)

或者

要捕获1到6的数字范围,

re2 := regexp.MustCompile(`[!.](\d{1,6})`)
英文:

You must remove the end of the line anchor $ since it won't be a line end after exactly 6 digits. For to capture exactly 6 digits, the quantifier must be

re2 := regexp.MustCompile(`[!.](\d{6})`)

Note that, this would also the digits which exists next to !. If you don't want this behaviour, you must remove the ! from the charcater class like

re2 := regexp.MustCompile(`[.](\d{6})`)

or

For to capture digits ranges from 1 to 6,

re2 := regexp.MustCompile(`[!.](\d{1,6})`)

huangapple
  • 本文由 发表于 2015年9月14日 00:59:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/32552224.html
匿名

发表评论

匿名网友

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

确定