英文:
Regex pattern that ensures that atleast one character is present along with other conditions
问题
我正在尝试根据以下三个条件验证一个字符串:
- 它必须包含一个字符串。
- 除了
.
和-
之外,它不应包含任何特殊字符。 - 数字是允许的,但不是必需的。
我使用试错法形成了这个正则表达式 ^(?=.*[a-zA-Z])[a-zA-Z0-9\.\- ]*$
,并且它在所有可用于测试的在线工具中都有效。但是我无法在代码中使用它。
错误信息显示:
panic: regexp: Compile(`^(?=.*[a-zA-Z])[a-zA-Z0-9\.\- ]*$`): error parsing regexp: invalid or unsupported Perl syntax: `(?=`
尽管它在其他在线工具中有效。我该如何修复这个问题?
英文:
I am trying to validate a string based on the three conditions below
- It must contain a string
- It should not contain any special characters except
.
and-
. - Numbers are allowed but not necessary
I formed this regex ^(?=.*[a-zA-Z])[a-zA-Z0-9\.\- ]*$
with the help of hit and trial. And it works in all the online tools available for testing. But I am not able to use this in the code
package main
import (
"fmt"
"regexp"
)
func main() {
rule := regexp.MustCompile(`^(?=.*[a-zA-Z])[a-zA-Z0-9\.\- ]*$`).MatchString
fmt.Println(rule("test_string"))
}
The error says
panic: regexp: Compile(`^(?=.*[a-zA-Z])[a-zA-Z0-9\.\- ]*$`): error parsing regexp: invalid or unsupported Perl syntax: `(?=`
Even though it works in other online tools. How can I fix this?
答案1
得分: 0
go语言不支持前后环视断言,但是你可以通过匹配允许的字符来省略环视断言。
你可以匹配一个单个字符A-Za-z,之前可以选择匹配任何允许的字符。
^[0-9. -]*[a-zA-Z][a-zA-Z0-9. -]*$
解释
^
字符串的开始[0-9. -]*
可选择匹配任何不包含a-zA-Z的允许字符[a-zA-Z]
匹配一个单个的a-zA-Z字符[a-zA-Z0-9. -]*
可选择匹配所有允许的字符$
字符串的结束
package main
import (
"fmt"
"regexp"
)
func main() {
rule := regexp.MustCompile(`^[0-9. -]*[a-zA-Z][a-zA-Z0-9. -]*$`).MatchString
fmt.Println(rule("test_string"))
fmt.Println(rule("this is a test"))
}
输出
false
true
英文:
go does not support lookaround assertions, but you can omit the lookarounds by matching the allowed characters.
You can match a single char A-Za-z between optionally matching any of the allowed characters.
^[0-9. -]*[a-zA-Z][a-zA-Z0-9. -]*$
Explanation
^
Start of string[0-9. -]*
Optionally match any of the allowed chars without a-zA-Z[a-zA-Z]
Match a single char a-zA-Z[a-zA-Z0-9. -]*
Optionally match any of all the allowed chars$
End of string
package main
import (
"fmt"
"regexp"
)
func main() {
rule := regexp.MustCompile(`^[0-9. -]*[a-zA-Z][a-zA-Z0-9. -]*$`).MatchString
fmt.Println(rule("test_string"))
fmt.Println(rule("this is a test"))
}
Output
false
true
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论