Finding Index of the Regular Expression present in Slice of Golang


In Golang, you can use regular expressions to search for a pattern in a string. The regexp package provides functionality to work with regular expressions. In this tutorial, we will learn how to find the index of the regular expression present in the slice of Golang.

Step 1: Importing the Required Packages

To use the regexp package, you need to import it first. You can import it using the following code −

import "regexp"

Step 2: Creating a Slice

Next, we will create a slice of strings. This slice will contain the strings in which we will search for the regular expression.

package main
import (
   "fmt"
   "regexp"
)

func main() {
   slice := []string{
      "The quick brown fox",
      "jumps over the lazy dog",
      "1234567890",
      "hello world",
   }
}

Step 3: Creating a Regular Expression

Now, we will create a regular expression that we want to search for in the slice.

package main

import (
   "fmt"
   "regexp"
)

func main() {
   slice := []string{
      "The quick brown fox",
      "jumps over the lazy dog",
      "1234567890",
      "hello world",
   }
   
   re := regexp.MustCompile(`\d+`)
}

In this example, we have created a regular expression that will match any sequence of digits.

Step 4: Searching for the Regular Expression

Now, we will loop through the slice and search for the regular expression in each string.

Example

package main

import (
   "fmt"
   "regexp"
)

func main() {
   slice := []string{
      "The quick brown fox",
      "jumps over the lazy dog",
      "1234567890",
      "hello world",
   }
    
   re := regexp.MustCompile(`\d+`)
    
   for i, str := range slice {
      match := re.FindStringIndex(str)
      if match != nil {
         fmt.Printf("Match found in slice[%d] at index %d\n", i, match[0])
      } else {
         fmt.Printf("No match found in slice[%d]\n", i)
      }
   }
}

In this example, we are using the FindStringIndex() function of the regexp package to search for the regular expression in each string of the slice. This function returns the starting and ending indices of the leftmost match of the regular expression in the string.

Output

No match found in slice[0]
No match found in slice[1]
Match found in slice[2] at index 0
No match found in slice[3]

Conclusion

In this tutorial, we have learned how to find the index of the regular expression present in the slice of Golang using the regexp package. With this knowledge, you can easily search for a pattern in a slice of strings in Golang.

Updated on: 17-Apr-2023

67 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements