Checking the string for the specified regular expression in Golang


Regular expressions are an essential aspect of programming, and they are widely used for pattern matching in various programming languages, including Golang. In Golang, strings are a sequence of bytes that represent Unicode characters. In this article, we will discuss how to check a string for the specified regular expression in Golang.

Checking String for Regular Expression

To check a string for the specified regular expression in Golang, we can use the "regexp" package. This package provides functions for compiling, matching, and replacing regular expressions.

The "regexp" package provides a function called "Compile" that takes a string as input and compiles the regular expression pattern into a regular expression object that can be used for pattern matching. We can then use the "MatchString" function of the "regexp" package to check whether the string matches the regular expression pattern.

Example

Here is an example of checking a string for the specified regular expression −

package main

import (
   "fmt"
   "regexp"
)

func main() {
   s := "Hello, World!"
   pattern := "llo"

   re, err := regexp.Compile(pattern)
   if err != nil {
      fmt.Println("Error compiling regular expression")
      return
   }
   
   if re.MatchString(s) {
      fmt.Printf("String contains the pattern '%s'\n", pattern)
   } else {
      fmt.Printf("String does not contain the pattern '%s'\n", pattern)
   }
}

Output

String contains the pattern 'llo'

In the above example, we have created a string "s" containing the value "Hello, World!" and a regular expression pattern "llo". We have then compiled the regular expression pattern into a regular expression object using the "Compile" function of the "regexp" package. We have then used the "MatchString" function of the "regexp" package to check whether the string "s" matches the regular expression pattern.

If the string matches the regular expression pattern, the program will output "String contains the pattern 'llo'". If the string does not match the regular expression pattern, the program will output "String does not contain the pattern 'llo'".

Conclusion

In this article, we have discussed how to check a string for the specified regular expression in Golang. We have used the "regexp" package to compile the regular expression pattern into a regular expression object and the "MatchString" function to check whether the string matches the regular expression pattern. By using the "regexp" package, we can easily perform pattern matching on strings in Golang.

Updated on: 17-Apr-2023

227 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements