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’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
Matches "Go", "Python" or "Java".
Matches a word or a 4-digit postal code.
Matches a string starting or ending with "from" or "to".
Notes
,
Operator. If grouping is required, use brackets ()
.
If there is no expression after the
The
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!