How to match and extract URLs or email addresses from a text using regular expressions in Golang?

To match and extract URLs or email addresses from text using regular expressions in Golang, you can use the regexp package. Here's an example for each case:

  1. Matching and extracting URLs:
package main import ( "fmt" "regexp" ) func main() { text := "Visit my website at https://example.com. You can also check https://google.com" // Regular expression pattern to match URLs urlPattern := `(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^ \n\r\t<\"]*[^.,;:\s<\"">\)\]\s]))` // Compiling the regular expression pattern r, err := regexp.Compile(urlPattern) if err != nil { fmt.Printf("Error compiling regex pattern: %v\n", err) return } // Extracting URLs from the text urls := r.FindAllString(text, -1) // Printing the extracted URLs for _, url := range urls { fmt.Println(url) } }

In this example, the FindAllString function is used to find all occurrences of the URL pattern in the given text. The urlPattern regular expression pattern is used to match URLs. The (?i) flag is used to enable case-insensitive matching.

  1. Matching and extracting email addresses:
package main import ( "fmt" "regexp" ) func main() { text := "Contact me at [email protected] or [email protected]" // Regular expression pattern to match email addresses emailPattern := `\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b` // Compiling the regular expression pattern r, err := regexp.Compile(emailPattern) if err != nil { fmt.Printf("Error compiling regex pattern: %v\n", err) return } // Extracting email addresses from the text emails := r.FindAllString(text, -1) // Printing the extracted email addresses for _, email := range emails { fmt.Println(email) } }

In this example, the FindAllString function is used to find all occurrences of the email pattern in the given text. The emailPattern regular expression pattern is used to match email addresses.

Note: The patterns provided in these examples are basic and may not cover all possible variations of valid URLs or email addresses. You may need to adjust the regular expressions according to your specific requirements.