Home  >  Article  >  Backend Development  >  How to match multiple words or strings using Golang regular expression?

How to match multiple words or strings using Golang regular expression?

WBOY
WBOYOriginal
2024-05-31 10:32:38391browse

Golang regular expressions use the pipe character | to match multiple words or strings, separating each option as a logical OR expression. For example: matches "fox" or "dog": fox|dog matches "quick", "brown" or "lazy": (quick|brown|lazy) matches "Go", "Python" or "Java": Go|Python |Java matches a word or 4-digit postal code: ([a-zA-Z] |1[0-9]{3}) matches a string starting or ending with "from" or "to": (^[Ff] ro?m)|([Tt]o)$

如何用 Golang 正则匹配多个单词或字符串?

How to use Golang regular expression to match multiple words or strings

Golang’s regular expressions provide The | (pipe character) operator is used to match multiple words or strings. The | operator separates each option into a logical OR expression.

Matching Code

import (
    "fmt"
    "regexp"
)

func main() {
    text := "The quick brown fox jumped over the lazy dog."

    // 匹配 "fox" 或 "dog"
    matched, err := regexp.MatchString("fox|dog", text)
    if err != nil {
        fmt.Println(err)
        return
    }
    // 输出:true

    // 匹配 "quick"、"brown" 或 "lazy"
    matched, err = regexp.MatchString("(quick|brown|lazy)", text)
    if err != nil {
        fmt.Println(err)
        return
    }
    // 输出:true
}

More Examples

  • ##(Go|Python|Java) Matches "Go", "Python" or "Java".
  • ([a-zA-Z] |1[0-9]{3}) Matches a word or a 4-digit postal code.
  • (^[Ff]ro?m)|([Tt]o)$ Matches a string starting or ending with "from" or "to".

Notes

    ##|
  • operator precedence is higher than , Operator. If grouping is required, use brackets (). If there is no expression after the
  • |
  • operator, an error will be thrown. The
  • |
  • operators in regular expressions also have other meanings in contexts other than string matching. Please use it with caution according to specific usage scenarios.

The above is the detailed content of How to match multiple words or strings using Golang regular expression?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn