java 不允许在开始时使用空格的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7826847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:35:33  来源:igfitidea点击:

regular expression for not allowing white space at start

javaregex

提问by user679526

A regular expression to allow only alphabets and numbers and spaces only in between alphabets with a maximum size of 20.

一个正则表达式,只允许字母和数字以及字母之间的空格,最大大小为20

([a-zA-Z0-9]+([\\s][a-zA-Z0-9]+)*){0,20}.

([a-zA-Z0-9]+([\\s][a-zA-Z0-9]+)*){0,20}.

This does not allow white space at start, but it is not checking the max size condition. How can I change this regular expression?

这在开始时不允许有空格,但它不会检查最大大小条件。如何更改此正则表达式?

回答by tripleee

You are specifying 20 repetitions of the entire pattern. I am guessing you probably mean something like

您正在指定整个模式的 20 次重复。我猜你的意思可能是

[a-zA-Z0-9][\sa-zA-Z0-9]{0,19}

If empty input should be allowed, wrap the whole thing in (...)?.

如果应该允许空输入,请将整个内容包装在(...)?.

回答by Code Jockey

All Sorts of ways to write this, and since you're using Java, why not use a Java regex "feature"? :D

各种各样的方法来写这个,既然你使用的是 Java,为什么不使用 Java 正则表达式“功能”?:D

String regexString = "(?<!\s+)[\w\s&&[^_]]{0,20}";

Broken down, this says:

分解,这说:

(?<!\s+)  # not following one or more whitespace characters,
[          # match one of the following:
  \w      # word character (`a-z`, `A-Z`, `0-9`, and `_`)
  \s      # whitespace characters
  &&[^_]   # EXCEPT FOR `_`
]          # 
{0,20}     # between 0 and 20 times

It will match a-z, A-Z, 0-9, and white space, even though the \w would otherwise include underscores, the extra part there says NOT underscores - I think it's unique to Java... anyways, that was fun!

它将匹配a-zA-Z0-9和空格,即使 \w 否则会包含下划线,那里的额外部分表示 NOT 下划线 - 我认为它是 Java 独有的......无论如何,这很有趣!

回答by FailedDev

The regex below :

下面的正则表达式:

boolean foundMatch = subjectString.matches("(?i)^(?=.{1,20}$)[a-z0-9]+(?:\s[a-z0-9]+)*$");

will match a string of 1 to 20 characters starting with an alphanumeric character followed by a single space and more alphanumeric characters. Note that the string must end with an alphanumeric character and not a space.

将匹配 1 到 20 个字符的字符串,以字母数字字符开头,后跟单个空格和更多字母数字字符。请注意,字符串必须以字母数字字符而不是空格结尾。