从字符串中提取数字集合的正则表达式,当前缀出现时,不匹配该前缀。

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

Regex extracting sets of numbers from string when prefix occurs, while not matching said prefix

问题

如标题所述,假设我有一个字符串:

"somestring~200~122"

我想要使用正则表达式匹配出前缀为"~"的数字,以便最终得到[200, 122]。

匹配前缀是必要的,因为我需要防止匹配下面这种情况的字符串:

"somestring~abc200~def122"

额外的背景信息:如标题所述,我正在使用Go语言,所以我计划使用以下代码来获取字符串中的数字:

pattern := regexp.MustCompile("我需要帮助的正则表达式")
numbers := pattern.FindAllString(host, -1)
英文:

As stated in the title, given a situation where I have a string like so:

"somestring~200~122"

I am wanting to regex to match the numbers when the prefix "~" occurs. So I can ultimately end up with [200, 122].

Matching the prefix is necessary as I need to protect against a case where a string like the one below should not be matched

"somestring~abc200~def122"

For additional context: As stated in the title, I am using go so I am planning on using doing something like the following in order to obtain the numbers within the string:

pattern := regexp.MustCompile("regex i need help with")
numbers := pattern.FindAllString(host, -1)

答案1

得分: 2

你可以使用FindAllStringSubmatch来提取只包含数字的组。下面是一个示例,它查找所有以~开头的数字,并将所有匹配项转换为整数并插入到一个切片中:

package main

import (
	"fmt"
	"regexp"
	"strconv"
)

func main() {
	host := "somestring~200~122"
	pattern := regexp.MustCompile(`~(\d+)`)
	numberStrings := pattern.FindAllStringSubmatch(host, -1)
	numbers := make([]int, len(numberStrings))
	for i, numberString := range numberStrings {
		number, err := strconv.Atoi(numberString[1])
		if err != nil {
			panic(err)
		}
		numbers[i] = number
	}
	fmt.Println(numbers)
}

这里是一个可以运行的示例。

英文:

You can use FindAllStringSubmatch to extract the group containing just the digits. Below is an example that finds all instances of ~ followed by numbers. It additionally converts all the matches to ints
and inserts them into a slice:

package main

import (
	"fmt"
	"regexp"
	"strconv"
)

func main() {
	host := "somestring~200~122"
	pattern := regexp.MustCompile(`~(\d+)`)
	numberStrings := pattern.FindAllStringSubmatch(host, -1)
	numbers := make([]int, len(numberStrings))
	for i, numberString := range numberStrings {
		number, err := strconv.Atoi(numberString[1])
		if err != nil {
			panic(err)
		}
		numbers[i] = number
	}
	fmt.Println(numbers)
}

https://play.golang.org/p/09YyewtRXz

huangapple
  • 本文由 发表于 2017年9月1日 01:39:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/45987254.html
匿名

发表评论

匿名网友

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

确定