英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论