Marco Grabmüller
Marco Grabmüller

Reputation: 53

Java regex - allow only if n digits in group from long string

i need a regex which allows a string, unless there are 6 or more numbers in a group at any point.

my current wrong regex:

^([a-zA-Z ]*)|(\d{0,5})$

match:

teststring 12345
teststring
1234 teststring
teststring 123 teststring
test1234string

not match:

1234567 teststring
teststring 123456
test123456789string

i hope someone can help. thx guys


UPDATE: this regex does the job:

^(?!.*\d{6}).*$

thx @WiktorStribiżew

Upvotes: 3

Views: 81

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

The pattern to match a string that has no 6 consecutive digits is

^(?!.*\d{6}).*

The regex demo is available here. If there can be line breaks inside, you need to add a DOTALL modifier that will make . match all chars including line break chars: (?s)^(?!.*\d{6}).*.

Details

  • ^ - start of string (implicit in matches())
  • (?!.*\d{6}) - a negative lookahead that fails the match if there are 0+ chars as many as possible followed with 6 consecutive digits
  • .* - any 0+ chars as many as possible

In Java, you may use it in the following way:

Boolean found = s.matches("(?s)(?!.*\\d{6}).*");

Note you may just try to find 6 digits with Matcher#find and if not found, proceed with the code excecution:

if (!Pattern.compile("\\d{6}").matcher(s).find()) {
    // Cool, proceed
}

Upvotes: 2

Wray Zheng
Wray Zheng

Reputation: 997

What about this regex:

^(\D*)\d{0,5}(\D*)$

Upvotes: 0

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59960

You can replace first group which match \d{6,} then check the result length with original length :

String text = "1234567 teststring";
boolean check = text.replaceFirst("\\d{6,}", "").length() == text.length();

Upvotes: 0

Related Questions