4

Hi I am having trouble trying to create a regex that will allow me to have the field empty or a string with length 9 if populated.

The current regex im using is: ^[0-9]{9}

Which works if the field is mandatory, however we have a new requirement that this can also be empty. I've tried ^[0-9]{0|9} but obviously that doesnt work.

Thanks in advance

4
  • 2
    Just make a normal string comparison to test whether the value is empty. No need for a regular expression here. Commented Apr 18, 2012 at 13:06
  • @FelixKling That requires JS, but doesn't work with <input pattern= Commented Apr 18, 2012 at 13:15
  • @Pumbaa80: Why do you assume that the expression is used in the context of JavaScript or even HTML? There is no indication of that in the question. Commented Apr 18, 2012 at 13:19
  • Right. I was trying to say that it may be impossible to test for an empty string by other means than the RegEx. Commented Apr 18, 2012 at 13:31

1 Answer 1

7
^(|[0-9]{9})$

Should do the trick.

Edit: But seriously; do what @Felix Kling suggests in a comment: test the string via a .length property, .equals("") or the like.

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

2 Comments

Great, thanks Jensgram. Not sure if it is because of the application im developing for but it doesn't allow me to use that expression. However tweeking your regex a bit it worked. Cheers! ^(|\d{9})$
@Redseven Great. Didn't realize this was related to the HTML5 pattern attribute.

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.