可匹配任何字符的Golang Regex 点'.'字符程序

122 阅读2分钟

概述

点'.'字符是正则表达式中最常使用的元字符之一。它被用来匹配任何字符。默认情况下,它不匹配新行。

程序

现在让我们来看看一个关于点'.'字符的简单程序

package main

import (
	"fmt"
	"regexp"
)

func main() {
	sampleRegexp := regexp.MustCompile(".")

	match := sampleRegexp.Match([]byte("a"))
	fmt.Printf("For a: %t\n", match)

	match = sampleRegexp.Match([]byte("b"))
	fmt.Printf("For b: %t\n", match)

	match = sampleRegexp.Match([]byte("ab"))
	fmt.Printf("For ab: %t\n", match)

	match = sampleRegexp.Match([]byte(""))
	fmt.Printf("For empty string: %t\n", match)
}

输出

For a: true
For b: true
For ab: true
For empty string: false

在上面的程序中,我们有一个只包含一个点字符的简单的重合规则。

sampleRegexp := regexp.MustCompile(".")

它匹配以下字符和字符串。

a
b
ab

它匹配的是ab ,因为默认情况下,除非我们使用锚定字符(Caret和Dollar字符),否则该词不会匹配整个字符串。这就是为什么它匹配'ab'中的第一个字符'a'并报告匹配结果。

它不会匹配一个空字符串。

让我们看看另一个例子,在这个词中我们有两个点。

package main

import (
	"fmt"
	"regexp"
)

func main() {
	sampleRegexp := regexp.MustCompile("..")
	match := sampleRegexp.Match([]byte("ab"))
	fmt.Printf("For ab: %t\n", match)

	match = sampleRegexp.Match([]byte("ba"))
	fmt.Printf("For ba: %t\n", match)

	match = sampleRegexp.Match([]byte("abc"))
	fmt.Printf("For abc: %t\n", match)

	match = sampleRegexp.Match([]byte("a"))
	fmt.Printf("For a: %t\n", match)
}

输出

For ab: true
For ba: true
For abc: true
For a: false

在上面的程序中,我们有一个包含两个点的简单词组。

sampleRegexp := regexp.MustCompile("..")

它将匹配任何给定的、至少有两个字符作为子串的字符串。

这就是为什么它能匹配到

ab
ba
abc

而没有匹配到

a

正如我们之前提到的,点**'.'**也不匹配新行。但是默认行为可以通过在正则表达式的开头添加一组标志来改变。我们需要添加到regex开头的标志是。

(?s)

让我们看一个同样的程序

package main

import (
	"fmt"
	"regexp"
)

func main() {
	sampleRegexp := regexp.MustCompile(".")

	match := sampleRegexp.Match([]byte("\n"))
	fmt.Printf("For \\n: %t\n", match)

	sampleRegexp = regexp.MustCompile("(?s).")

	match = sampleRegexp.Match([]byte("\n"))
	fmt.Printf("For \\n: %t\n", match)
}

输出

For \n: false
For \n: true
sampleRegexp := regexp.MustCompile(".")

sampleRegexp = regexp.MustCompile("(?s).")

在第二个regex中,我们添加了额外的标志。这就是为什么它给出了一个新行的匹配,而第一个没有标志的regex却没有给出一个匹配。