Go Regular Expression Demonstration

GoGoBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

This challenge demonstrates how to use regular expressions in Golang.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Go`")) -.-> go/AdvancedTopicsGroup(["`Advanced Topics`"]) go/AdvancedTopicsGroup -.-> go/regular_expressions("`Regular Expressions`") subgraph Lab Skills go/regular_expressions -.-> lab-15422{{"`Go Regular Expression Demonstration`"}} end

Regular Expressions

The challenge requires you to complete the code to perform various regular expression-related tasks in Golang.

Requirements

  • Use the regexp package to perform regular expression-related tasks.
  • Use MatchString to test whether a pattern matches a string.
  • Use Compile to optimize a Regexp struct.
  • Use MatchString to test a match like Compile.
  • Use FindString to find the match for the regexp.
  • Use FindStringIndex to find the first match and return the start and end indexes for the match instead of the matching text.
  • Use FindStringSubmatch to return information for both p([a-z]+)ch and ([a-z]+).
  • Use FindStringSubmatchIndex to return information about the indexes of matches and submatches.
  • Use FindAllString to find all matches for a regexp.
  • Use FindAllStringSubmatchIndex to apply to all matches in the input, not just the first.
  • Use Match to test a match with []byte arguments and drop String from the function name.
  • Use MustCompile to create global variables with regular expressions.
  • Use ReplaceAllString to replace subsets of strings with other values.
  • Use ReplaceAllFunc to transform matched text with a given function.

Example

$ go run regular-expressions.go
true
true
peach
idx: [0 5]
[peach ea]
[0 5 1 3]
[peach punch pinch]
all: [[0 5 1 3] [6 11 7 9] [12 17 13 15]]
[peach punch]
true
regexp: p([a-z]+)ch
a <fruit>
a PEACH

## For a complete reference on Go regular expressions check
## the [`regexp`](https://pkg.go.dev/regexp) package docs.

Summary

This challenge demonstrates how to use regular expressions in Golang to perform various tasks such as testing whether a pattern matches a string, finding the match for the regexp, and replacing subsets of strings with other values.

Other Go Tutorials you may like