C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Pattern: We use some metacharacters in the pattern. The period means "any character" and the plus means "one or more."
Result: The first return value (matched) is a boolean that is true if the pattern matched. The second is an error value (which may be nil).
Golang program that uses regexp.MatchString
package main
import (
"fmt"
"regexp"
)
func main() {
value := "cat"
// See if this regular expression matches.
matched, _ := regexp.MatchString(".+t", value)
// Test the result.
if matched {
fmt.Println(true)
}
}
Output
true
MustCompile: This method compiles a regular expression and returns the instance. It will cause an error (panic) if the pattern is invalid.
Here: We loop over the strings in a slice and attempt to match each string with the compiled regular expression.
SliceGolang program that compiles regexp and uses MatchString
package main
import (
"fmt"
"regexp"
)
func main() {
// Compile this regular expression.
var lettersDigits = regexp.MustCompile(`\w\w\w\d\d\d`)
// Some strings to test.
values := []string{"cat100", "dog200",
"bird", "200fish"}
// Loop over our strings and call MatchString on them.
for i := range values {
result := lettersDigits.MatchString(values[i])
fmt.Printf("%v = %v\n", values[i], result)
}
}
Output
cat100 = true
dog200 = true
bird = false
200fish = false
Argument 1: This is the string we want to split. This should have delimiters (like commas or spaces).
Argument 2: The second argument to Split() is the maximum number of substrings to get. We use a negative number to indicate no limit.
Golang program that uses Split, regexp
package main
import (
"fmt"
"regexp"
)
func main() {
value := "carrot,cat;dog"
// Compile the delimiter as a regular expression.
re := regexp.MustCompile(`\W`)
// Call split based on the delimiter pattern.
// ... Get all substrings.
result := re.Split(value, -1)
// Display our results.
for i := range(result) {
fmt.Println(result[i])
}
}
Output
carrot
cat
dog