0

I have one string like 010000200000, 000000200000, 020000200000. I want to create regex for this and want to check that first 2 digit will be only 01,00 & 02. And rest of the digit should be only from [0-6].

I don't want any space or any special character in this string. I try some of the regex available online but didn't help me exactly.

If anyone has any idea please kindly help.

1
  • 1
    see answers below, but mind that this is not alphanumeric, as there are no letters :) Commented Dec 7, 2012 at 13:32

5 Answers 5

5

This should parse them with your requirements.

java.util.regex.Pattern.matches("0[012][0-6]+", "010000200000");

The first character is always a 0, followed by 1 character that is a 0, 1 or 2, followed by at least 1 character in the 0-6 range.

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

Comments

3

Straightforward

"0[012][0-6]*"

Start with 0, next a 0, 1 or 2, and than any amount of digits between 0 and 6.

Comments

1

I recommend you have a look at this tutorial.

If the number of digits and number of segments of your string is fixed, you could use

(?:0[012][0-6]{10}, ){2}0[012][0-6]{10}

If they are not, simply

(?:0[012][0-6]*, )*0[012][0-6]*

If you actually meant the given example is three separate strings, then it's even easier:

0[012][0-6]{10}

or

0[012][0-6]*

All this uses is character classes and repetition.

Note that these will only behave as you like when you use them with Pattern.matches. If not, surround them with ^...$ to make sure there is nothing else in front of or after this pattern.

Comments

0
java.util.regex.Pattern.matches("0[0-2]{1}[3-6]{10}", "015453356543")    

This is the what exactly needed regular expression...yes?

1 Comment

No. 0-2 is also allowed for the 10 trailing digits. And the {1} is (always) redundant.
-1

What about 0[0-2][0-6][0-6][0-6][0-6][0-6][0-6][0-6][0-6][0-6][0-6]? Obviously I guessed you need a fixed length string of 12 chars, otherwise 0[0-2][0-6]+ would be ok.

1 Comment

fixed length can also be achieved by using quantifiers. Will make it much more readable, so yours would be 0[0-2][0-6]{10}

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.