Golang正则表达式匹配+-/ *

时间:2018-06-20 02:09:09

标签: regex go

我尝试过:

re_operator := regexp.MustCompile("^(+|-|*|/)")

我明白了:

panic: regexp: Compile(`^(+|-|*|/)`): error parsing regexp: missing argument to repetition operator: `+`

对于这个问题,谷歌实际上是不可能的,更不用说每种语言和版本的问题了。我将使用if否则。转义序列也是一种痛苦。我应该尝试转义转义序列吗?

无益的答案: Regular expression to match digits and basic math operators

1 个答案:

答案 0 :(得分:4)

转义RegEx元字符:

MustCompile("^(\\+|-|\\*|/)")

或更妙的是,使用方括号表达式:

MustCompile("^[-+*/]")

请注意,在方括号表达式中,您必须首先或最后加上连字符。