[英]Java Regex match space before or after characters
I try to have a regex validating an input field. 我尝试使用正则表达式验证输入字段。
This question is the continuation of this question but I made a mistake and the question changed a bit so I created a new one. 这个问题是延续了这个问题 ,但我犯了一个错误,问题改变了一点,所以我创建了一个新的。
Here is my java regex : 这是我的java正则表达式:
^(?:\?*[a-zA-Z\d]){2}[a-zA-Z\d?]*\*?$
What I'm tying to match is : 我想要匹配的是:
So for exemple :
例如:
- abcd = OK
abcd =好的
- ?bcd = OK
?bcd =好的
- ab??
AB? = OK
=好的
- ab*= OK
ab * =好的
- ab?* = OK
ab?* =好的
- ??cd = OK
?? cd = OK
- ab cd = OK
ab cd =好的
- *ab = NOT OK
* ab =不行
- a ?
一种 ? b =NOT OK
b =不行
- ???
??? = NOT OK
=不行
- ab?
AB? cd = NOT OK
cd =不行
- ab ?d = NOT OK
ab?d =不行
- ab * = NOT OK
ab * =不行
- abcd = NOT OK (space at the begining)
abcd =不行(开头的空间)
As i've asked in the fisrt question, no white space at all are allowed in my regex now but that's not what I want and I'm a bit lost can you help me please? 正如我在fisrt问题中提出的那样,现在我的正则表达式中根本没有空白区域,但这不是我想要的,我有点迷失你能帮我吗?
You may use 你可以用
^(?!\s)(?!.*\s[*?])(?!.*[*?]\s)(?:[?\s]*[a-zA-Z0-9]){2}[a-zA-Z0-9?\s]*\*?$
See the regex demo . 请参阅正则表达式演示 。
Usage note : if you use it with Java's .matches()
method, the ^
and $
can be removed from the pattern. 使用说明 :如果将其与Java的
.matches()
方法一起使用,则可以从模式中删除^
和$
。 Remember to double escape backslashes in the string literal. 请记住在字符串文字中双重转义反斜杠。
Details 细节
^
- start of string ^
- 字符串的开头 (?!\\s)
- no whitespace is allowed immediately to the right (at the start of the string) (?!\\s)
- 不允许立即向右的空格(在字符串的开头) (?!.*\\s[*?])
- no whitespace is allowed after any 0+ chars, as many as possible, before *
or ?
(?!.*\\s[*?])
- 在*
或?
之前,任何0+字符之后不允许有空格?
(?!.*[*?]\\s)
- no whitespace is allowed after any 0+ chars, as many as possible, after *
or ?
(?!.*[*?]\\s)
- 在*
或?
之后,任何0+字符后都不允许有空格?
(?:[?\\s]*[a-zA-Z0-9]){2}
- two sequences of (?:[?\\s]*[a-zA-Z0-9]){2}
- 两个序列
[?\\s]*
- 0 or more ?
[?\\s]*
- 0或更多?
or/and whitespaces [a-zA-Z0-9]
- an alphanumeric char [a-zA-Z0-9]
- 一个字母数字字符 [a-zA-Z0-9?\\s]*
- 0 or more letters, digits, ?
[a-zA-Z0-9?\\s]*
- 0个或更多字母,数字, ?
or whitespaces \\*?
- an optional ?
?
char $
- end of the string. $
- 字符串的结尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.