具有"Joker"的Java Regex;人物 [英] Java Regex with "Joker" characters
问题描述
我尝试让正则表达式验证输入字段. 我所说的小丑"字符是?"和 '*'. 这是我的Java正则表达式:
I try to have a regex validating an input field. What i call "joker" chars are '?' and '*'. Here is my java regex :
"^$|[^\\*\\s]{2,}|[^\\*\\s]{2,}[\\*\\?]|[^\\*\\s]{2,}[\\?]{1,}[^\\s\\*]*[\\*]{0,1}"
我想匹配的是:
- 至少2个字母数字字符(?"和"*"除外)
- "*"只能出现一次,并且只能出现在字符串的末尾
- ?"可以出现多次
- 完全没有空格
- abcd =确定
- ?bcd =确定
- ab ??? =确定
- ab * =确定
- ab?* =确定
- ?? cd =好
- * ab =不合适
- ??? =不好
- ab cd =不正确
- abcd =不正确(开头是空格)
- abcd = OK
- ?bcd = OK
- ab?? = OK
- ab*= OK
- ab?* = OK
- ??cd = OK
- *ab = NOT OK
- ??? = NOT OK
- ab cd = NOT OK
- abcd = Not OK (space at the begining)
我使正则表达式有点复杂,我迷路了,你能帮我吗?
I've made the regex a bit complicated and I'm lost can you help me?
推荐答案
^(?:\?*[a-zA-Z\d]\?*){2,}\*?$
说明:
正则表达式断言该模式必须出现两次或多次:
The regex asserts that this pattern must appear twice or more:
\?*[a-zA-Z\d]\?*
断言[a-zA-Z\d]
类中必须有一个字符,其左侧或右侧带有0到无穷大问号.
which asserts that there must be one character in the class [a-zA-Z\d]
with 0 to infinity questions marks on the left or right of it.
然后,正则表达式在字符串的末尾匹配\*?
,这意味着0或1个星号字符.
Then, the regex matches \*?
, which means an 0 or 1 asterisk character, at the end of the string.
这是一个更快的替代正则表达式,正如revo在评论中建议的那样:
Here is an alternative regex that is faster, as revo suggested in the comments:
^(?:\?*[a-zA-Z\d]){2}[a-zA-Z\d?]*\*?$
这篇关于具有"Joker"的Java Regex;人物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!