1 回答

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超5個(gè)贊
您需要使用捕獲組來(lái)捕獲該句子的內(nèi)容:
package main
import "fmt"
import "regexp"
func main() {
str := `
* * *
Match this line
`
r, _ := regexp.Compile(`\* \* \*\n.*\n(.*)`)
fmt.Println(r.FindStringSubmatch(str)[1])
}
輸出:
Match this line
解釋?zhuān)?/p>
\* \* \* Matches the first line containing the asterisks.
\n A newline.
.* Second line. Can be anything (Likely the line is simply empty)
\n A newline
( Start of capturing group
.* The content of interest
) End of capturing group
在評(píng)論中,您詢問(wèn)如何將第三行替換為<hr/>. 在這種情況下,我將使用兩個(gè)捕獲組 - 一個(gè)用于感興趣線之前的部分,另一個(gè)用于線本身。在替換模式中,您可以使用$1結(jié)果中的第一個(gè)捕獲組的值。
例子:
package main
import "fmt"
import "regexp"
func main() {
str := `
* * *
Match this line
`
r, _ := regexp.Compile(`(\* \* \*\n.*\n)(.*)`)
str = string(r.ReplaceAll([]byte(str), []byte("$1<hr/>")))
fmt.Println(str)
}
- 1 回答
- 0 關(guān)注
- 230 瀏覽
添加回答
舉報(bào)