JavaDeveloper
JavaDeveloper

Reputation: 5660

How to match Golang regex over multiple lines when there is new line character?

package main

import (
    "fmt"
    "regexp"
)

func main() {
        r, _ := regexp.Compile(`OWASP_CSRFTOKEN:([a-zA-Z0-9\-]+)`)
        str := "OWASP_CSRFTOKEN:A-a-**\n**9-!OWASP_CSRFTOKEN:B-b-8-"
        fmt.Printf("%q\n", r.FindString(str))
}

I am trying to match a pattern. Note \n in the str variable. I am not able to match the pattern OWASP_CSRFTOKEN:([a-zA-Z0-9\-]+) because of \n in str variable.

The string which I expect to match is OWASP_CSRFTOKEN:A-a-9-, but I get a match for OWASP_CSRFTOKEN:A-a- since 9- is after \n

Upvotes: 4

Views: 5709

Answers (1)

Eugene Lisitsky
Eugene Lisitsky

Reputation: 12845

Try multi-line mode:

package main

import (
    "fmt"
    "regexp"
)

func main() {
        r, _ := regexp.Compile("(?m)OWASP_CSRFTOKEN:([a-zA-Z0-9*-]+)")
        str := "OWASP_CSRFTOKEN:A-a-**\n**9-!OWASP_CSRFTOKEN:B-b-8-"
        fmt.Printf("%q\n", r.FindString(str))
}

Output:

"OWASP_CSRFTOKEN:A-a-**"
  • or allow \n matching as any character - turn on with s flag
package main

import (
    "fmt"
    "regexp"
)

func main() {
        r, _ := regexp.Compile("(?s)OWASP_CSRFTOKEN:([a-zA-Z0-9*\n-]+)")
        str := "OWASP_CSRFTOKEN:A-a-**\n**9-!OWASP_CSRFTOKEN:B-b-8-"
        fmt.Printf("%q\n", r.FindString(str))
}

Output:

"OWASP_CSRFTOKEN:A-a-**\n**9-"

(Also I've added * as allowed character)

Upvotes: 10

Related Questions