golang正则匹配a=rtpmap:39 H264/90000并找到其中的39
时间: 2024-02-20 20:58:39 浏览: 25
可以使用正则表达式来匹配字符串并提取其中的子串。在 Golang 中,可以使用 `regexp` 包来进行正则表达式的匹配。
以下是一个示例代码:
```go
package main
import (
"fmt"
"regexp"
)
func main() {
str := "a=rtpmap:39 H264/90000"
re := regexp.MustCompile(`a=rtpmap:(\d+)`)
match := re.FindStringSubmatch(str)
if len(match) > 1 {
fmt.Println(match[1])
}
}
```
输出结果为:
```
39
```
其中,`regexp.MustCompile` 函数用于编译正则表达式,`(\d+)` 是一个捕获组,用于匹配一个或多个数字,`FindStringSubmatch` 函数用于在字符串中查找符合正则表达式的子串,并返回一个包含子串和捕获组的切片。最后,可以通过切片的索引来获取捕获组中的值。
相关问题
golang正则匹配a=rtpmap:(\d+) H264/90000并替换其中的数字
好的,我可以帮你解决这个问题。你可以使用golang标准库中的regexp包来进行正则匹配和替换。下面是一个示例代码:
```go
package main
import (
"fmt"
"regexp"
)
func main() {
str := "a=rtpmap:123 H264/90000"
re := regexp.MustCompile(`a=rtpmap:(\d+) H264/90000`)
result := re.ReplaceAllString(str, "a=rtpmap:456 H264/90000")
fmt.Println(result)
}
```
这段代码中,我们首先定义了一个字符串 `str`,它包含了一个符合要求的字符串。然后我们使用 `regexp.MustCompile` 函数来编译正则表达式,这里的正则表达式是 `a=rtpmap:(\d+) H264/90000`,其中 `\d+` 匹配一个或多个数字。接着我们使用 `re.ReplaceAllString` 函数来替换匹配到的数字部分,将其替换为 `456`。最后输出结果即可。
你可以根据自己的需求修改代码中的正则表达式和替换字符串。希望能帮到你。
golang正则匹配b=开头\n结尾
在 Golang 中,可以使用 `regexp` 包来进行正则表达式匹配。以下是匹配以 `b=` 开头,以 `\n` 结尾的正则表达式示例代码:
```go
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`^b=.*\n$`)
str := "b=hello world\n"
if re.MatchString(str) {
fmt.Println("Matched!")
} else {
fmt.Println("Not matched!")
}
}
```
在上面的代码中,我们使用 `regexp.MustCompile()` 函数创建了一个正则表达式对象,然后使用 `MatchString()` 方法对指定的字符串进行匹配。如果匹配成功,输出 `Matched!`;否则输出 `Not matched!`。