简体   繁体   English

Java Regex在字符之前或之后匹配空格

[英]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?]*\*?$

Demo 演示

What I'm tying to match is : 我想要匹配的是:

  • Minimum 2 alpha-numeric characters (other than '?' and '*') 至少2个字母数字字符(“?”和“*”除外)
  • The '*' can only appears one time and at the end of the string '*'只能出现一次并出现在字符串的末尾
  • The '?' '?' can appears multiple time 可以出现多次
  • No WhiteSpace right at the beginning 开始时没有WhiteSpace
  • No WhiteSpace before or after '?' 在'?'之前或之后没有WhiteSpace or '*' 要么 '*'

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM