Java Regex - 不是空字符串,只有数字,8 个字符长

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

Java Regex - Not an empty string, only numbers, 8 chars long

javaregex

提问by deanmau5

I'm trying to construct a regex that basically allows only numbers, 8 characters long and cannot be empty ie "" or have 8 blank spaces

我正在尝试构建一个基本上只允许数字、8 个字符长且不能为空的正则表达式,即“”或有 8 个空格

I've been able to get two separate regex that will nearly do what I'm after: ^(?!\s*$).+which does not allow empty strings, but permits white space. Also: ^[0-9]+$which lets me only search for numbers.

我已经能够得到两个单独的正则表达式,它们几乎可以满足我的要求: ^(?!\s*$).+不允许空字符串,但允许空格。另外:^[0-9]+$这让我只能搜索数字。

I would like to combine these regex expression and also and in a clause to match strings that are 8 characters long.

我想将这些正则表达式和 和 结合在一个子句中以匹配 8 个字符长的字符串。

Any advice on how I could combine what I have so far?

关于如何结合我迄今为止所拥有的任何建议?

回答by Pshemo

Just place ^(?!\s*$)at start of your regex. Try this way ^(?!\s*$)[0-9\s]{8}$?

只需放在^(?!\s*$)正则表达式的开头即可。试试这个方法^(?!\s*$)[0-9\s]{8}$

  • ^(?!\s*$)as you know will check if entire string is not only white spaces
  • [0-9\s]will match any digit and white space
  • {8}means exactly 8 occurrences of element before it (in our case digit or white space)
  • ^(?!\s*$)如您所知,将检查整个字符串是否不仅是空格
  • [0-9\s]将匹配任何数字和空格
  • {8}意味着在它之前正好出现 8 次元素(在我们的例子中是数字或空格)

回答by Sergio

Can't really get how the string can be 8 characters long and contain only digits and be whitespace, but for matching just 8 digits try this one:

无法真正了解字符串如何可以是 8 个字符长且仅包含数字和空格,但要匹配仅 8 个数字,请尝试以下方法:

^\d{8}$

回答by Derek Peterson

You can specify a quantifier that ensures that your pattern will match a certain number of digits like so: ^[0-9]{8}$.

您可以指定一个量词确保您的模式将匹配一定数量的数字,像这样:^[0-9]{8}$

Edit:Hm, I misread the part about white space before. Is it alright for there to be white space within the string to be matched, or just around it? If the former, I'll have to re-work my answer. If the latter, drop the ^and $.

编辑:嗯,我之前误读了关于空白的部分。在要匹配的字符串中或在它周围有空格是否可以?如果是前者,我将不得不重新回答我的问题。如果是后者,去掉^$

Edit v2:Pshemo has the day.

编辑 v2:Pshemo 有今天。

回答by Toilal

^[\d|\s]{8}$

^[\d|\s]{8}$

or in java ...

或在Java中...

String re = "^[\d|\s]{8}$";

回答by fge

First do a length check on the string to see if it's eigth chars long ;)

首先对字符串进行长度检查,看看它是否是第 8 个字符长;)

Then trim (to remove spaces at the beginning and end) and match with \d+(\s+\d+)*:

然后修剪(删除开头和结尾的空格)并匹配\d+(\s+\d+)*

// No need to anchor the regex since we use .matches()
return input.length() == 8 && input.trim().matches("\d+(\s+\d+)*");