Skip to content

Commit 8abbe93

Browse files
committed
Updated
1 parent 178d0f4 commit 8abbe93

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

golang-regex-replace-split.md

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
title: Golang regex: Replace and split
2+
tags: golang,golang-regex
3+
4+
You can use the ReplaceAllString methods to replace a string, and manipulate groups if needed.
5+
6+
rp := regexp.MustCompile("([a-z]+) ([a-z]+)")
7+
rp.ReplaceAllString("abc def ghi", "$2 $1") // "def abc ghi"
8+
9+
$1 relates to the first group match, and $2 the same. You could just enter text to replace the entireity of the "abc def" string.
10+
11+
ReplaceAllLiteralString allows you to interpret the dollar sign literally.
12+
13+
You can also use a function to do the replacement. You cannot use a groups here, however, as of 1.1.1 anyway.
14+
15+
rp.ReplaceAllStringFunc("abc def", func(s string) string {
16+
if(s=="abc") {
17+
return "HA"
18+
}
19+
return s
20+
}) // "HA def"
21+
22+
You can split a string using the Split method. The second integer argument is the number of splits to perform. -1 means as many as possible.
23+
24+
rp = regexp.MustCompile("a")
25+
i := rp2.Split("zzzzazzzzz", -1) // ["zzzz", "zzzz"]

0 commit comments

Comments
 (0)