java 字符串的Java正则表达式以数字和固定长度开头

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

Java Regex of String start with number and fixed length

javaregex

提问by waseem

I made a regular expression for checking the length of String , all characters are numbers and start with number e.g 123 Following is my expression

我做了一个正则表达式来检查 String 的长度,所有字符都是数字并以数字开头,例如 123 以下是我的表达式

REGEX =^123\d+{9}$";

But it was unable to check the length of String. It validates those strings only their length is 9 and start with 123. But if I pass the String 1234567891 it also validates it. But how should I do it which thing is wrong on my side.

但它无法检查字符串的长度。它仅验证这些字符串的长度为 9 并以 123 开头。但如果我传递字符串 1234567891,它也会验证它。但是我应该怎么做,哪件事情在我这边是错误的。

回答by pcalcao

Like already answered here, the simplest way is just removing the +:

就像这里已经回答的一样,最简单的方法就是删除+

^123\d{9}$

or

或者

^123\d{6}$

Depending on what you need exactly.

完全取决于您的需求。

You can also use another, a bit more complicated and generic approach, a negative lookahead:

您还可以使用另一种更复杂和通用的方法,即否定前瞻:

(?!.{10,})^123\d+$

Explanation:

解释:

This: (?!.{10,})is a negative look-ahead(?=would be a positive look-ahead), it means that if the expression after the look-ahead matches this pattern, then the overall string doesn't match. Roughly it means: The criteria for this regular expression is only met if the pattern in the negative look-ahead doesn't match.

这:(?!.{10,})是一个否定的前瞻?=将是一个肯定的前瞻),这意味着如果前瞻之后的表达式匹配这个模式,那么整个字符串不匹配。粗略地说,它的意思是:仅当否定前瞻中的模式不匹配时,才满足此正则表达式的条件

In this case, the string matches onlyif .{10}doesn't match, which means 10 or more characters, so it only matches if the pattern in front matches up to 9 characters.

在这种情况下,字符串.{10}不匹配时才匹配,这意味着 10 个或更多字符,因此仅当前面的模式匹配最多 9 个字符时才匹配。

A positive look-ahead does the opposite, only matching if the criteria in the look-ahead alsomatches.

积极的前瞻做相反的事情,只有在前瞻中的标准匹配时才匹配。

Just putting this here for curiosity sake, it's more complex than what you need for this.

只是为了好奇而把它放在这里,它比你需要的更复杂。

回答by Doorknob

Try using this one:

尝试使用这个:

^123\d{6}$

I changed it to 6because 1, 2, and 3 should probably still count as digits.

我将其更改为6因为 1、2 和 3 可能仍应计为数字。

Also, I removed the +. With it, it would match 1 or more \ds (therefore an infinite amount of digits).

另外,我删除了+. 有了它,它将匹配 1 个或多个\ds(因此是无限数量的数字)。

回答by jlordo

Based on your comment below Doorknobs's answeryou can do this:

根据您在Doorknobs 回答评论,您可以执行以下操作:

int length = 9;
String prefix = "123"; // or whatever
String regex = "^" + prefix + "\d{ " + (length - prefix.length()) + "}$";
if (input.matches(regex)) {
    // good
} else {
    // bad
}