I'm a Go beginner and I've been playing with regexes. Example:
r, _ := regexp.Compile(`\* \* \*`)
r2 := r.ReplaceAll(b, []byte("<hr>"))
(Replace all * * *
s for <hr>
s)
One thing that I have no idea how to do is to find the next
item after an occurence. In JavaScript/jQuery I used to do this:
$("#input-content p:has(br)").next('p').doStuff()
(Find the next p
tag
after a p
tag that has a br
tag inside).
What's the simplest way to accomplish the same in Go? Say, finding the next line after * * *
?
* * * Match this line
You would need to use a capturing group to grap the contents of that sentence:
package main
import "fmt"
import "regexp"
func main() {
str := `
* * *
Match this line
`
r, _ := regexp.Compile(`\* \* \*
.*
(.*)`)
fmt.Println(r.FindStringSubmatch(str)[1])
}
Output:
Match this line
Explanation:
\* \* \* Matches the first line containing the asterisks.
A newline.
.* Second line. Can be anything (Likely the line is simply empty)
A newline
( Start of capturing group
.* The content of interest
) End of capturing group
In comments you asked how to replace the third line by <hr/>
. In this case I would use two capturing groups - one for the part before the line of interest and one for the line itself. In the replacement pattern you can then use $1
to use the value of the first capturing group in the result.
Example:
package main
import "fmt"
import "regexp"
func main() {
str := `
* * *
Match this line
`
r, _ := regexp.Compile(`(\* \* \*
.*
)(.*)`)
str = string(r.ReplaceAll([]byte(str), []byte("$1<hr/>")))
fmt.Println(str)
}