Home ยป How to Split String by Regex in Golang

How to Split String by Regex in Golang

The Golang package regexp implements regular expression search. It has a Split function that splits a string by regex expression into substrings. It returns the slice of substrings between those regex matches.

Syntax

func (re *Regexp) Split(s string, n int) []string

Where,

s = given string

n = specify the count of substrings to return

Returns string array.

In this article, we will discuss how to split a string by regex using the regex Split() function.

How to Split String Using Regex in Golang

Use the Golang regexp package built-in Split method that takes two arguments; a string and a count to determine substrings to return. It splits the string based on the regex expression.

package main

import (
	"fmt"
	"regexp"
)

func main() {

	// Declare a string with whitespaces

	str := "C#,Python,    Golang"

	// Use the regular expression to extracts all text except white space
	regex1 := regexp.MustCompile(",\\S*")
	fmt.Println("All text without white space:", regex1.Split(str, -1))

	// Use the regex to extracts all white spaces only
	regex2 := regexp.MustCompile(",\\s*")
	fmt.Println("All White Space only:", regex2.Split(str, -1))

}

In the above golang program, it imports the regexp package to use the Split and fmt package.

To split the string by regex in a string using regex Split(), follow the below steps:

  1. Declare string s1
  2. Create an object of RegExp by using regexp.MustCompile()
  3. RegExp object has a Split method which takes a string and splits it into a substring based on the regular expression.
  4. In the first example, it uses regex \\S* to extract all text except white space and returns C# Golang
  5. In the second example, it uses regex \\s* to extract all white spaces only

The output of the above golang program to split a string by regex is:

All text without white space: [C#     Golang]

All White Space only: [C# Python Golang]

Cool Tip: How to split a string with multiple separators in Golang!

Conclusion

I hope the above article on how to split a string by regex using the RegExp Split() function is helpful to you.

You can find more topics about the Golang tutorials on the GolangSpot Home page.

Leave a Comment