Java 正则表达式 - 匹配具有零个或一个空格的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24699616/
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
Regex - Match a string which has zero or one spaces
提问by crazyfool
I'm trying to match a string which starts with @, can contain any amount of letters or numbers but can only contain a maximum of one space (or zero spaces). So far I have
我试图匹配一个以@ 开头的字符串,可以包含任意数量的字母或数字,但最多只能包含一个空格(或零个空格)。到目前为止我有
@([A-Za-z0-9]+)
which matches the characters but without the space. I think I need \s{0,1} but I'm not sure where to put it.. Can anyone help?
匹配字符但没有空格。我想我需要 \s{0,1} 但我不知道把它放在哪里..有人可以帮忙吗?
Thanks.
谢谢。
采纳答案by Adam Yost
Assuming you only care about spaces in the word, not leading or trailing then you could use this:
假设你只关心单词中的空格,而不是前导或尾随,那么你可以使用这个:
@[A-Za-z0-9]* ?[A-Za-z0-9]*
Explanation:
解释:
@
Starts with literal @
@
以文字@开头
[A-Za-z0-9]
Any letter or number
[A-Za-z0-9]
任何字母或数字
*
Letter or number can be length {0,infinity}
*
字母或数字的长度可以是 {0,infinity}
?
Space char, 0 or one times
?
空格字符,0 或 1 次
[A-Za-z0-9]*
Any number of trailing letters or spaces after the space (if there is one)
[A-Za-z0-9]*
空格后任意数量的尾随字母或空格(如果有)
回答by Avinash Raj
回答by anubhava
You can use this regex with negative lookahead:
您可以将此正则表达式与负前瞻一起使用:
^@((?!(?:\S* ){2})[A-Za-z0-9 ]+)$