Reputation: 331
I want to get all work in string - that are between the pair of {word}
Example:
payment://pay?id={appid}&transtoken={transtoken}
Result expect:
["appid", "transtoken"]
With regex partern: {\w+}
, I only can get [{appid}, {transtoken}]
.
Please help me with the problem.
Upvotes: 2
Views: 1019
Reputation: 626748
You may use the following pattern with FindAllStringSubmatch
:
{(\w+)}
See the Go regexp documentation:
FindAllStringSubmatch
is the 'All' version ofFindStringSubmatch
; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.
and
FindStringSubmatch
returns a slice of strings holding the text of the leftmost match of the regular expression ins
and the matches, if any, of its subexpressions, as defined by the 'Submatch' description in the package comment. A return value of nil indicates no match.
See the Go demo:
package main
import (
"fmt"
"regexp"
)
func main() {
s := `payment://pay?id={appid}&transtoken={transtoken}`
rex := regexp.MustCompile(`{(\w+)}`)
results := rex.FindAllStringSubmatch(s,-1)
for _, value := range results {
fmt.Printf("%q\n", value[1])
}
}
Output:
"appid"
"transtoken"
Upvotes: 4