golang:使用regex返回字符串之间的最短字符串 [英] golang: Use regex to return the shortest string between strings
问题描述
我有字符串:
123abc456def456
我想返回 123和456,即abc。我试过FindStringSubmatch:
package main
import(
fmt
regexp
)
func main(){
re:= regexp.MustCompile(123(。*)456)
fmt.Printf( %q\\\
,re.FindStringSubmatch(123abc456def456))
}
它只返回最长的字符串:
$ b
[123abc456def456abc456def]
如何返回最短字符串abc?
*
是 贪婪 操作符,意思是它会匹配尽可能多,并仍然允许正则表达式的其余部分匹配。使用 *?
表示零或多个 - 优选尽可能少的非贪婪匹配。
一旦你指定了问号,你就说明了(只要你找到数字4......停止,你就完成了。)
p> re:= regexp.MustCompile(123(。*?)456)
rm:= re.FindStringSubmatch( 123abc456def456)
fmt.Printf(%q,rm)// [123abc456abc]
或者只打印最短匹配,我会这样做:
re:= regexp。 MustCompile(123(。*?)456)
rm:= re.FindStringSubmatch(123abc456def456)
if len(rm)!= 0 {fmt.Printf(%q,rm [1])} //abc
I have string:
"123abc456def456"
I would like to return the shortest string between "123" and "456", which is "abc". I tried FindStringSubmatch:
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile("123(.*)456")
fmt.Printf("%q\n", re.FindStringSubmatch("123abc456def456"))
}
It only returns the longest string:
["123abc456def456" "abc456def"]
How to return the shortest string "abc"?
*
is a greedy operator meaning it will match as much as it can and still allow the remainder of the regular expression to match. Use *?
for a non-greedy match meaning "zero or more — preferably as few as possible".
Once you specify the question mark, you're stating (as soon as you find the number "4" ... stop, you're finished.)
re := regexp.MustCompile("123(.*?)456")
rm := re.FindStringSubmatch("123abc456def456")
fmt.Printf("%q", rm) // ["123abc456" "abc"]
Or to print only the shortest match itself, I would do:
re := regexp.MustCompile("123(.*?)456")
rm := re.FindStringSubmatch("123abc456def456")
if len(rm) != 0 {fmt.Printf("%q", rm[1])} // "abc"
这篇关于golang:使用regex返回字符串之间的最短字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!