Search code examples
regexgore2

Regex to match after string before space using RE2


I am new to RE2 syntax regex, I want to match first word comes after specific string.

For example:

java.lang.OutOfMemoryError: Java heap space Error sending periodic event java.lang.NullPointerException: Java heap space Error sending periodic event

I want to capture anything comes after java.lang. so I can get OutOfMemoryError, NullPointerException errors. I know in Python and PCRE we can do this using positive lookbehind and regex will be - (?<=java.lang.).*?(?=\s), but this is not working for RE2.


Solution

  • You may use

    java\.lang\.([^\s:]+)
    

    Details

    • java\.lang\. - a java.lang. substring
    • ([^\s:]+) - Capturing group 1: one or more characters other than whitespace and :.

    NOTE: If you need to get all text between java.lang. and : followed with whitespace, use java\.lang\.(.*?):\s.

    See the regex demo and the Go demo:

    package main
    
    import (
        "fmt"
        "regexp"
    )
    
    func main() {
        regex := regexp.MustCompile(`java\.lang\.([^\s:]+)`)
        result := regex.FindStringSubmatch("java.lang.OutOfMemoryError: Java heap space Error sending periodic event")
        fmt.Printf("%q", result[1])
    }