Golang Regexp.FindString
最后修改于 2025 年 4 月 20 日
本教程将介绍如何在 Go 中使用 Regexp.FindString
方法。我们将涵盖基本用法并提供查找字符串匹配的实际示例。
一个 正则表达式 是一个定义搜索模式的字符序列。它用于在字符串中进行模式匹配。
Regexp.FindString
方法返回正则表达式在输入字符串中的第一个匹配项。如果没有找到匹配项,则返回空字符串。
FindString 基本示例
FindString
最简单的用法是查找模式的第一个匹配项。这里我们在字符串中搜索一个简单的单词。
package main import ( "fmt" "regexp" ) func main() { re := regexp.MustCompile(`hello`) match := re.FindString("hello there, hello world") fmt.Println(match) // "hello" noMatch := re.FindString("goodbye") fmt.Println(noMatch) // "" }
我们编译模式 "hello" 并使用 FindString
查找第一个出现的位置。它会返回匹配的子字符串或空字符串。
在文本中查找数字
本示例演示了如何使用 FindString
在字符串中查找第一个数字。
package main import ( "fmt" "regexp" ) func main() { re := regexp.MustCompile(`\d+`) text := "The price is 42 dollars and 99 cents" match := re.FindString(text) fmt.Printf("First number found: %s\n", match) // "42" }
模式 \d+
匹配一个或多个数字。FindString
在输入字符串中仅返回第一个匹配项。
查找电子邮件地址
我们可以使用 FindString
从文本中提取第一个电子邮件地址。
package main import ( "fmt" "regexp" ) func main() { pattern := `[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}` re := regexp.MustCompile(pattern) text := "Contact us at support@example.com or sales@company.org" email := re.FindString(text) fmt.Println("First email found:", email) // "support@example.com" }
电子邮件模式匹配标准的电子邮件格式。FindString
在找到输入文本中的第一个匹配项后停止。
不区分大小写的匹配
本示例展示了如何使用 FindString
执行不区分大小写的匹配。
package main import ( "fmt" "regexp" ) func main() { re := regexp.MustCompile(`(?i)hello`) match1 := re.FindString("Hello world") match2 := re.FindString("hElLo there") noMatch := re.FindString("Goodbye") fmt.Println(match1) // "Hello" fmt.Println(match2) // "hElLo" fmt.Println(noMatch) // "" }
(?i)
标志使模式不区分大小写。该方法仍然返回匹配子字符串的原始大小写。
查找 HTML 标签
本示例演示了如何在字符串中查找第一个 HTML 标签。
package main import ( "fmt" "regexp" ) func main() { re := regexp.MustCompile(`<[^>]+>`) html := `<div>This is <b>bold</b> text</div>` tag := re.FindString(html) fmt.Println("First HTML tag:", tag) // "<div>" }
该模式匹配尖括号之间的任何内容。FindString
返回在输入中找到的第一个完整的 HTML 标签。
查找以特定前缀开头的单词
本示例查找以特定前缀开头的第一个单词。
package main import ( "fmt" "regexp" ) func main() { re := regexp.MustCompile(`\bun\w*\b`) text := "The universe is unknown but not uninteresting" match := re.FindString(text) fmt.Println("First 'un' word:", match) // "universe" }
模式 \bun\w*\b
匹配以 "un" 开头的整个单词。FindString
返回找到的第一个这样的单词。
在文本中查找第一个 URL
本示例从一段文本中提取第一个 URL。
package main import ( "fmt" "regexp" ) func main() { pattern := `https?://[^\s]+` re := regexp.MustCompile(pattern) text := `Visit https://example.com or http://test.org for more info` url := re.FindString(text) fmt.Println("First URL found:", url) // "https://example.com" }
该模式匹配 HTTP/HTTPS URL。FindString
返回在输入文本中找到的第一个完整的 URL。
来源
本教程通过查找文本中字符串匹配的实际示例,涵盖了 Go 中的 Regexp.FindString
方法。