Can someone tell me how to validate sequence of numbers with one space and at the end there will be a optional special character say \'#\' and again followed by some 5 digit
This question isn't very clear, but macek's suggestion does in fact answer your question about how to add the optional tag of '#' followed by some number of digits at the end, so you should try that. (Specifically, (?:#\d+)?$
is the relevant portion of the regex; (?:#\d{0,5})?$
will ensure that between 0 and 5 digits are present.)
However, your regex for ensuring that there are exactly 1 space and at most 12 digits before the optional '#' is incorrect. The lookahead, as written, is meaningless, because \d{0,11}
will match the 0-width string at the beginning of any string (since this is equivalent to 0 digits). What you need is something like /^(?:[\d\s]{1,13}$)\d*\s\d*$/
. This will check to make sure that the right number of characters is present and that they are all either digits or spaces, then it will check that there is only one space in the string. There's a bit of redundancy here, but that shouldn't be a problem. Also, note that I'm using \s
instead of a space character for clarity, but note that this will match tabs and other whitespace, which may not be what you want. The digit count of {1,13}
assumes that it is legal for the string to consist of a single space with no digits at all, but the empty string is illegal; adjust the values in the brackets if this is not the correct assumption.
Finally, to combine the above regex for ensuring the proper space-and-digit count with the regex for the optional tag, you'll need to change the lookahead so that it can match #
as well as $
: it should be /^(?:[\d\s]{1,13}(#|$))\d*\s\d*(#\d{0,5})?$/
.
(Please note that I haven't actually tested the above regex, so I'm not 100% sure that the (#|$)
in the middle will work with all implementations. If it doesn't, it can be replaced with a redundant (#\d{0,5})?
.)
This should do the trick
/^\d+\s\d+(?:#\d+)?$/
See it on rubular
^ beginning of string
\d+ one or more numbers
\s any whitespace character
\d+ one or more numbers
(?: begin non-capturing group
# literal '#' character
\d+ one or more numbers
) end non-capturing group
$ end of string
/^0[\d\s]{,11}(?:#\d{,5}?$/
Matches a string starting with 0
, followed by a max of 11 numbers or spaces. Followed by an optional #
with a max of 5 numbers after it.