2

I need to check a string with a regex.

the valid strings are for example: ABC0001 or A00023.

There are three parts I have to check:

  1. So the string should start with a word signs: [a-zA-Z]{1,}
  2. Then there are min one zero: [0]{1,}
  3. The third part is a number \\d+

The whole string may not be longer than 8 signs.

What I tried so far:

String NR_PATTERN = "^([a-zA-Z]{1,}[0]{1,}\\d+){3,8}$";

The problem is, that the regex do not accepts the string: KDS0234

3
  • And the trouble you have with this expression is (other than the fact that you can have arbitrary length strings by inserting zeros or additional letters and that [0] is the same as bare-bones 0)? Commented Jul 8, 2016 at 8:38
  • 1
    "^([a-zA-Z]{1,}[0]{1,}\\d+){3,8}$"; mean ([a-zA-Z]{1,}[0]{1,}\\d+) appear 3-8 times, not whole length is 3-8 Commented Jul 8, 2016 at 8:44
  • Try like this: "^(?!.{9})[A-Z]+0+[1-9]\\d*$" Commented Jul 8, 2016 at 8:53

5 Answers 5

3

You could try with a positive lookahead in the beginning:

(?=^.{3,8}$)([a-zA-Z]{1,}[0]{1,}\\d+)

The positive lookahead:

(?=^.{3,8}$)

will look ahead ?= and confirm that from the beginnning ^ to the end $ of the string, there is any character matched by . between 3 and 8 times {3,8}.

Sign up to request clarification or add additional context in comments.

Comments

1

(…){3,8} means you want to … sequence to be repeated between 3 and 8 times, not that the string is 8 characters

You could just use ( in know you said you need a regex, but perhaps this will work for you)

String NR_PATTERN = "[a-zA-Z]+0+\\d+";
String s = "ABC0001";
boolean match  = s.length() < 8 &&  s.matches(NR_PATTERN);

Comments

1

You can check the length condition with a lookahead and then match your pattern:

\b(?=[a-zA-Z0-9]{3,8})([A-Za-z]+0[0-9]+)\b

Comments

1

You could go for:

\b(?=[A-Z]+0+\d+)\w{3,8}\b

See a demo on regex101.com, in Java use double backslashes.


This will match:

ABC0001 A00023 and ABCD001

But not

B123456 or 0001B

1 Comment

In the OP: "The whole string may not be longer than 8 signs."
0
(?=^.{3,8}$)([a-zA-Z]+[0]+\d+)

Hope this help

2 Comments

Please edit with more information. Code-only and "try this" answers are discouraged, because they contain no searchable content, and don't explain why someone should "try this". We make an effort here to be a resource for knowledge.
Although this code may be help to solve the problem, providing additional context regarding why and/or how it answers the question would significantly improve its long-term value. Please edit your answer to add some explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.