Go Package regexp: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
No edit summary
 
(8 intermediate revisions by the same user not shown)
Line 1: Line 1:
=External=
=External=


* https://golang.org/pkg/regexp
* https://pkg.go.dev/regexp
* https://github.com/google/re2/wiki/Syntax


=Internal=
=Internal=


* [[Go_Language_Modularization#regexp|Standard Library]]
* [[Go_Language_Modularization#regexp|Standard Library]]
* [[Go_Regular_Expressions#Overview|Go Regular Expressions]]
=Overview=
<syntaxhighlight lang='go'>
import (
"regexp"
)
var someRegexp *regexp.Regexp
someRegexp = regexp.MustCompile("(\\D+)(\\d+),(\\d)")
groups := someRegexp.FindSubmatch([]byte(s))
if groups == nil {
  // no match
  ...
}
entireString := groups[0]
firstGroup := groups[1]
secondGroup := groups[2]
thirdGroup := groups[3]
</syntaxhighlight>


=Functions=
=Functions=


==<tt>regexp.MatchString()</tt>==
==Matching==


===<tt>regexp.MatchString()</tt>===
* <tt>[https://golang.org/pkg/regexp/#MatchString regexp.MatchString()]</tt>


* <tt>[https://golang.org/pkg/regexp/#MatchString regexp.MatchString()]</tt>
<syntaxhighlight lang=go>
var regex = regexp.MustCompile("^[_a-zA-Z][_a-zA-Z0-9]*$")
[...]
if regex.MatchString(s) {
  ...
}
</syntaxhighlight>
 
==Replacement==
Needs a Regexp instance.
===<tt>regexp.ReplaceAllString()</tt>===
<syntaxhighlight lang='go'>
func (re *Regexp) ReplaceAllString(src, repl string) string
</syntaxhighlight>
 
There is a <code>[[Go_Strings#Replace()|strings.Replace(...)]]</code> function, but it does not take regular expressions.
 
=TODO=
* https://blog.logrocket.com/deep-dive-regular-expressions-golang/
* https://gobyexample.com/regular-expressions

Latest revision as of 19:18, 29 April 2024

External

Internal

Overview

import (
	"regexp"
)

var someRegexp *regexp.Regexp
someRegexp = regexp.MustCompile("(\\D+)(\\d+),(\\d)")

groups := someRegexp.FindSubmatch([]byte(s))
if groups == nil {
  // no match 
  ...
}

entireString := groups[0]
firstGroup := groups[1]
secondGroup := groups[2]
thirdGroup := groups[3]

Functions

Matching

regexp.MatchString()

var regex = regexp.MustCompile("^[_a-zA-Z][_a-zA-Z0-9]*$")
[...]
if regex.MatchString(s) {
  ...
}

Replacement

Needs a Regexp instance.

regexp.ReplaceAllString()

func (re *Regexp) ReplaceAllString(src, repl string) string

There is a strings.Replace(...) function, but it does not take regular expressions.

TODO