3

Here i want to make regx for string which contains only 0 to 6 numbers only. This String contains 0 to 6 numbers like that.

 Example-1 : "010002030405" Valid String

This String contains only o to 6 numbers so here i used this regx "[0-6]*". But one more thing i want to validate in this string, I want 0 only at odd positions 1-6 will not be on odd positions never. 0 can be place on odd and even both but 1-6 will be place only even positions.

Here i given u some valid and invalid string examples

Valid : 000102000004
invalid : 0023015006

Here i used this code Please suggest me or tell me what i have to change in my regx to satisfy below validation

1) String contains only 0-6 numbers nothing else.
2) 1-6 would be only even positions only they would not be at odd position ever, 0 would be odd and even position.

Code :

public boolean isOptions(String input) {
    String patternString = "[0-6]*";
    Pattern pattern = Pattern.compile(patternString);
    return pattern.matcher(input).matches();
}
5
  • 1
    "I want 0 only at odd positions 1-6 will not be on odd positions never. 0 can be place on odd and even both" Isn't this a bit contradictory that you want 0 only at odd positions and that 0 can be placed at both odd and even? Commented Dec 10, 2012 at 5:39
  • are you really bent upon using regex here? I think simple loop and checking should be much easier here. Commented Dec 10, 2012 at 5:41
  • stackoverflow.com/questions/691519/… This would help lot to achieve the logic you trying to build Commented Dec 10, 2012 at 5:53
  • 1
    @Shreya: Wouldn't that also match "022222222"? Commented Dec 10, 2012 at 5:57
  • @Hyperboreus Sorry my bad. i want 0 at even and odd both and 1-6 only on even places. Commented Dec 10, 2012 at 6:24

1 Answer 1

7

Haven't tried this out, but might work:

(0[0-6])*0?
Sign up to request clarification or add additional context in comments.

6 Comments

how is it ensuring that 1-6 are only at even positions?
Because first comes a 0 and then anything between 0 and 6. Rinse and repeat (this pattern of 2 digits). Then maybe add a final 0.
@Hyperboreus Thanks Can u please Explain me this regular expresssion
This expression matches all strings that have 0 or more times a couple of "0" follow by a digit between 0 and 6; and maybe a trailing 0.
@Hyperboreus Here i want to check String validation for every 2 places. So what type of modification i have to make change?
|

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.