java 正则表达式中的空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5753142/
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 12:35:53  来源:igfitidea点击:

Blank spaces in regular expression

javaregexvalidation

提问by sfrj

I use this regular to validate many of the input fields of my java web app:

我使用这个常规来验证我的 java web 应用程序的许多输入字段:

"^[a-zA-Z0-9]+$"

But i need to modify it, because i have a couple of fields that need to allow blank spaces(for example: Address).

但我需要修改它,因为我有几个字段需要允许空格(例如:地址)。

How can i modify it to allow blank spaces(if possible not at the start).

我如何修改它以允许空格(如果可能的话不在开头)。

I think i need to use some scape character like \

我想我需要使用一些像 \

I tried a few different combinations but none of them worked. Can somebody help me with this regex?

我尝试了几种不同的组合,但都没有奏效。有人可以帮我处理这个正则表达式吗?

回答by darioo

I'd suggest using this:

我建议使用这个:

^[a-zA-Z0-9][a-zA-Z0-9 ]+$

It adds two things: first, you're guaranteed not to have a space at the beginning, while allowing characters you need. Afterwards, letters a-zand A-Zare allowed, as well as all digits and spaces (there's a space at the end of my regex).

它增加了两件事:首先,你保证开头没有空格,同时允许你需要的字符。之后,允许使用字母a-zA-Z,以及所有数字和空格(我的正则表达式末尾有一个空格)。

回答by Oscar Mederos

If you want to use only a whitespace, you can do:

如果只想使用空格,可以执行以下操作:

^[a-zA-Z0-9 ]+$

^[a-zA-Z0-9 ]+$

If you want to include tabs\t, new-line\n\r\ncharacters, you can do:

如果要包含tabs\t换行符\n\r\n,可以执行以下操作:

^[a-zA-Z0-9\s]+$

^[a-zA-Z0-9\s]+$

Also, as you asked, if you don't want the whitespace to be at the begining:

另外,正如您所问的,如果您不希望空格在开头

^[a-zA-Z0-9][a-zA-Z0-9 ]+$

^[a-zA-Z0-9][a-zA-Z0-9 ]+$

回答by Arnab Das

Use this: ^[a-zA-Z0-9]+[a-zA-Z0-9 ]+$. This should work. First atom ensures that there must be at least one character at beginning.

使用这个:^[a-zA-Z0-9]+[a-zA-Z0-9 ]+$。这应该有效。第一个原子确保开头必须至少有一个字符。

回答by Mahesh KP

try like this ^[a-zA-Z0-9 ]+$ that is, add a space in it

试试这样 ^[a-zA-Z0-9 ]+$ 即,在其中添加一个空格

回答by Gursel Koca

This regex dont allow spaces at the end of string, one downside it accepts underscore character also.

这个正则表达式不允许在字符串末尾有空格,一个缺点是它也接受下划线字符。

^(\w+ )+\w+|\w+$

回答by Lekensteyn

Try this one: I assume that any input with a length of at least one character is valid. The previously mentioned answers does not take that into account.

试试这个:我假设任何长度至少为一个字符的输入都是有效的。前面提到的答案没有考虑到这一点。

"^[a-zA-Z0-9][a-zA-Z0-9 ]*$"

If you want to allow all whitespace characters, replace the space by "\s"

如果要允许所有空格字符,请将空格替换为“\s”