本文整理汇总了Golang中regexp.Regexp.MatchString方法的典型用法代码示例。如果您正苦于以下问题:Golang Regexp.MatchString方法的具体用法?Golang Regexp.MatchString怎么用?Golang Regexp.MatchString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类regexp.Regexp
的用法示例。
在下文中一共展示了Regexp.MatchString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: testFindAllIndex
func testFindAllIndex(t *testing.T, tc *testCase, x *Index, rx *regexp.Regexp, n int) {
res := x.FindAllIndex(rx, n)
exp := rx.FindAllStringIndex(tc.source, n)
// check that the lengths match
if len(res) != len(exp) {
t.Errorf("test %q, FindAllIndex %q (n = %d): expected %d results; got %d", tc.name, rx, n, len(exp), len(res))
}
// if n >= 0 the number of results is limited --- unless n >= all results,
// we may obtain different positions from the Index and from regexp (because
// Index may not find the results in the same order as regexp) => in general
// we cannot simply check that the res and exp lists are equal
// check that each result is in fact a correct match and the result is sorted
for i, r := range res {
if r[0] < 0 || r[0] > r[1] || len(tc.source) < r[1] {
t.Errorf("test %q, FindAllIndex %q, result %d (n == %d): illegal match [%d, %d]", tc.name, rx, i, n, r[0], r[1])
} else if !rx.MatchString(tc.source[r[0]:r[1]]) {
t.Errorf("test %q, FindAllIndex %q, result %d (n = %d): [%d, %d] not a match", tc.name, rx, i, n, r[0], r[1])
}
}
if n < 0 {
// all results computed - sorted res and exp must be equal
for i, r := range res {
e := exp[i]
if r[0] != e[0] || r[1] != e[1] {
t.Errorf("test %q, FindAllIndex %q, result %d: expected match [%d, %d]; got [%d, %d]",
tc.name, rx, i, e[0], e[1], r[0], r[1])
}
}
}
}
示例2: Symbols
func (f *file) Symbols(r *regexp.Regexp, addr uint64) ([]*plugin.Sym, error) {
if f.sym == nil {
sym, err := f.file.Symbols()
if err != nil {
return nil, err
}
f.sym = sym
}
var out []*plugin.Sym
for _, s := range f.sym {
// Ignore a symbol with address 0 and size 0.
// An ELF STT_FILE symbol will look like that.
if s.Addr == 0 && s.Size == 0 {
continue
}
if (r == nil || r.MatchString(s.Name)) && (addr == 0 || s.Addr <= addr && addr < s.Addr+uint64(s.Size)) {
out = append(out, &plugin.Sym{
Name: []string{s.Name},
File: f.name,
Start: s.Addr,
End: s.Addr + uint64(s.Size) - 1,
})
}
}
return out, nil
}
示例3: list
// list is a subcommand to list up snippets.
// It just finds snippet files in the snippet directory and listed them.
func list(c *cli.Context) {
var pattern *regexp.Regexp
var err error
query := c.Args().First()
if len(query) > 0 {
pattern, err = regexp.Compile(fmt.Sprintf(".*%s.*", query))
if err != nil {
log.Fatal(err)
}
}
err = filepath.Walk(
conf.SnippetDirectory,
func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
rel, err := filepath.Rel(conf.SnippetDirectory, path)
if pattern != nil {
if pattern.MatchString(rel) {
fmt.Println(rel)
}
return nil
}
fmt.Println(rel)
return nil
},
)
if err != nil {
log.Fatal(err)
}
}
示例4: checkAuth
func checkAuth(client <-chan string, result chan<- bool) {
var (
attempt int
data string
pass *regexp.Regexp
)
pass = regexp.MustCompile(`^(?i)PASS(?-i) ` + opt.Password + `\r?\n?$`)
attempt = 0
for data = range client {
if attempt > AuthAttempts {
log.Print("Authentication bad, tearing down.")
result <- false
return
}
if pass.MatchString(data) {
log.Print("Authentication good, open sesame.")
result <- true
return
}
attempt++
}
}
示例5: parseNetDevStats
func parseNetDevStats(r io.Reader, ignore *regexp.Regexp) (map[string]map[string]string, error) {
scanner := bufio.NewScanner(r)
scanner.Scan() // skip first header
scanner.Scan()
parts := strings.Split(string(scanner.Text()), "|")
if len(parts) != 3 { // interface + receive + transmit
return nil, fmt.Errorf("invalid header line in net/dev: %s",
scanner.Text())
}
header := strings.Fields(parts[1])
netDev := map[string]map[string]string{}
for scanner.Scan() {
line := strings.TrimLeft(string(scanner.Text()), " ")
parts := procNetDevFieldSep.Split(line, -1)
if len(parts) != 2*len(header)+1 {
return nil, fmt.Errorf("invalid line in net/dev: %s", scanner.Text())
}
dev := parts[0][:len(parts[0])]
if ignore.MatchString(dev) {
log.Debugf("Ignoring device: %s", dev)
continue
}
netDev[dev] = map[string]string{}
for i, v := range header {
netDev[dev]["receive_"+v] = parts[i+1]
netDev[dev]["transmit_"+v] = parts[i+1+len(header)]
}
}
return netDev, scanner.Err()
}
示例6: PruneFrom
// PruneFrom removes all nodes beneath the lowest node matching dropRx, not including itself.
//
// Please see the example below to understand this method as well as
// the difference from Prune method.
//
// A sample contains Location of [A,B,C,B,D] where D is the top frame and there's no inline.
//
// PruneFrom(A) returns [A,B,C,B,D] because there's no node beneath A.
// Prune(A, nil) returns [B,C,B,D] by removing A itself.
//
// PruneFrom(B) returns [B,C,B,D] by removing all nodes beneath the first B when scanning from the bottom.
// Prune(B, nil) returns [D] because a matching node is found by scanning from the root.
func (p *Profile) PruneFrom(dropRx *regexp.Regexp) {
pruneBeneath := make(map[uint64]bool)
for _, loc := range p.Location {
for i := 0; i < len(loc.Line); i++ {
if fn := loc.Line[i].Function; fn != nil && fn.Name != "" {
// Account for leading '.' on the PPC ELF v1 ABI.
funcName := strings.TrimPrefix(fn.Name, ".")
// Account for unsimplified names -- trim starting from the first '('.
if index := strings.Index(funcName, "("); index > 0 {
funcName = funcName[:index]
}
if dropRx.MatchString(funcName) {
// Found matching entry to prune.
pruneBeneath[loc.ID] = true
loc.Line = loc.Line[i:]
break
}
}
}
}
// Prune locs from each Sample
for _, sample := range p.Sample {
// Scan from the bottom leaf to the root to find the prune location.
for i, loc := range sample.Location {
if pruneBeneath[loc.ID] {
sample.Location = sample.Location[i:]
break
}
}
}
}
示例7: getSuffixMatches
func getSuffixMatches(req *http.Request, pattern *regexp.Regexp) bool {
if httputil.IsGet(req) {
suffix := httputil.PathSuffix(req)
return pattern.MatchString(suffix)
}
return false
}
示例8: TestIntegration
func TestIntegration(t *testing.T) {
flag.Parse()
bleve.Config.DefaultIndexType = *indexType
t.Logf("using index type %s", *indexType)
var err error
var datasetRegexp *regexp.Regexp
if *dataset != "" {
datasetRegexp, err = regexp.Compile(*dataset)
if err != nil {
t.Fatal(err)
}
}
fis, err := ioutil.ReadDir("tests")
if err != nil {
t.Fatal(err)
}
for _, fi := range fis {
if datasetRegexp != nil {
if !datasetRegexp.MatchString(fi.Name()) {
continue
}
}
if fi.IsDir() {
t.Logf("Running test: %s", fi.Name())
runTestDir(t, "tests"+string(filepath.Separator)+fi.Name(), fi.Name())
}
}
}
示例9: validateField
func validateField(name, cont string, whitelist *regexp.Regexp) error {
if !whitelist.MatchString(cont) {
return fmt.Errorf("app description field '%s' contains illegal %q (legal: '%s')", name, cont, whitelist)
}
return nil
}
示例10: matches
func (rules *Rules) matches(u string, options map[string]interface{}, generalRe *re.Regexp, domainRequiredRules map[string][]*Rule, rulesWithOptions []*Rule) bool {
if generalRe != nil && generalRe.MatchString(u) {
return true
}
rls := []*Rule{}
isrcDomain, ok := options["domain"]
srcDomain, ok2 := isrcDomain.(string)
if ok && ok2 && len(domainRequiredRules) > 0 {
for _, domain := range DomainVariants(srcDomain) {
if vs, ok := domainRequiredRules[domain]; ok {
rls = append(rls, vs...)
}
}
}
rls = append(rls, rulesWithOptions...)
if !rules.opt.CheckUnsupportedRules {
for _, rule := range rls {
if rule.MatchingSupported(options) {
if rule.MatchURL(u, options) {
return true
}
}
}
}
return false
}
示例11: Err
// Err ensures the error satisfies the given regular expression.
func Err(t Fataler, err error, re *regexp.Regexp, a ...interface{}) {
if err == nil && re == nil {
return
}
if err == nil && re != nil {
fatal(cond{
Fataler: t,
Format: `expected error: "%s" but got a nil error`,
FormatArgs: []interface{}{re},
Extra: a,
})
return
}
if err != nil && re == nil {
fatal(cond{
Fataler: t,
Format: `unexpected error: %s`,
FormatArgs: []interface{}{err},
Extra: a,
})
return
}
if !re.MatchString(err.Error()) {
fatal(cond{
Fataler: t,
Format: `expected error: "%s" but got "%s"`,
FormatArgs: []interface{}{re, err},
Extra: a,
})
}
}
示例12: Select
func (fc *AfmFontCollection) Select(family, weight, style string, ranges []string) (fontMetrics FontMetrics, err error) {
if len(ranges) > 0 {
return nil, errors.New("Named ranges not supported for Type1 fonts.")
}
var re *regexp.Regexp
if re, err = makeFontSelectRegexp(family, weight, style); err != nil {
return
}
if fc.Fonts == nil {
fc.Fonts = make(map[string]*afm.Font)
}
for _, f := range fc.FontInfos {
if re.MatchString(f.PostScriptName()) {
font := fc.Fonts[f.Filename]
if font == nil {
font, err = afm.LoadFont(f.Filename)
fc.Fonts[f.Filename] = font
}
fontMetrics = font
return
}
}
err = fmt.Errorf("Font '%s %s %s' not found", family, weight, style)
return
}
示例13: MakeTransportAddress
// Given an IP address and a port number, this function creates a transport address.
//
// INPUT
// - in_ip: IP address.
// - in_port: port number.
//
// OUTPUT
// - The transport address.
// - The error flag.
func MakeTransportAddress(in_ip string, in_port int) (string, error) {
var ipv4, ipv6 *regexp.Regexp
var err error
ipv4, err = regexp.Compile("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$")
if nil != err {
panic("Internal error.")
}
ipv6, err = regexp.Compile("^[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}$")
if nil != err {
panic("Internal error.")
}
// Is it IPV4?
if ipv4.MatchString(in_ip) {
return fmt.Sprintf("%s:%d", in_ip, in_port), nil
}
// Is it IPV6?
if ipv6.MatchString(in_ip) {
return fmt.Sprintf("[%s]:%d", in_ip, in_port), nil
}
return "", errors.New(fmt.Sprintf("Invalid IP address \"%s\"!", in_ip))
}
示例14: newWatcher
func newWatcher(path string, include, exclude *regexp.Regexp) (*watcher, error) {
events := make(chan notify.EventInfo, 10)
ops := make(chan Operation, 10)
if err := notify.Watch(path+"/...", events, notify.All); err != nil {
return nil, err
}
go func() {
for ev := range events {
if include.MatchString(ev.Path()) == false {
debug(fmt.Sprintf("Skipping: does not match include path: %s", ev.Path()))
continue
}
if exclude.MatchString(ev.Path()) == true {
debug(fmt.Sprintf("Skipping: does match exclude path: %s", ev.Path()))
continue
}
ops <- Operation{
Path: ev.Path(),
EventInfo: ev,
}
}
}()
return &watcher{ops: ops, events: events}, nil
}
示例15: re
func re(ctx *ScalarContext, nArg int) {
ad := ctx.GetAuxData(0)
var re *regexp.Regexp
if ad == nil {
reused = false
//println("Compile")
var err error
re, err = regexp.Compile(ctx.Text(0))
if err != nil {
ctx.ResultError(err.Error())
return
}
ctx.SetAuxData(0, re)
} else {
reused = true
//println("Reuse")
var ok bool
if re, ok = ad.(*regexp.Regexp); !ok {
println(ad)
ctx.ResultError("AuxData not a regexp")
return
}
}
m := re.MatchString(ctx.Text(1))
ctx.ResultBool(m)
}