且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

String的Java Regex以数字和固定长度开头

更新时间:2023-11-26 20:04:46

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

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

^123\\d{9}$

^123\\d{6}$

具体取决于您的需求。

你也可以使用另一种,更复杂和通用的方法,消极前瞻:

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

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

说明:

这: (?!。{10,})负面预测?= 会是一个积极的表情-ahead),这意味着如果前瞻后的表达式匹配此模式,则整个字符串不匹配。大致意味着:仅当负前瞻中的模式与不匹配时,才会满足此正则表达式的条件。

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.

In在这种情况下,字符串匹配如果。{10} 不匹配,这意味着10个或更多字符,所以它只匹配前面的模式最多匹配9个字符。

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

正向前瞻相反,只有在前瞻中的条件时才匹配>匹配。

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

出于好奇的缘故,将它放在这里,它比你需要的更复杂。

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