views:

80

answers:

2

I need a regex for four-digit numbers separated by comma ("default" can also be a value).

Examples:

  1. 6755
  2. 3452,8767,9865,8766,3454
  3. 7678,9876
  4. 1234,9867,6876,9865
  5. default

Note: "default" alone should match, but default,1234,7656 should NOT match.

+6  A: 

This should do it:

/^(default|\d{4}(,\d{4})*)$/

That's

^         start of string
(         start group
 default  literal "default"
 |        or
 \d{4}    digit repeated 4 times
  (       start group
   ,      literal ","
   \d{4}  four digits
  )       end group
 *        repeat 0 or more times
)         end group
$         end of string
Greg
Beat me to it by 15 seconds. ;-)
Sean Vieira
it does match anything not even 1234not even 1234,5678
Subhasis
Works for me at this regex test page: http://www.regular-expressions.info/javascriptexample.html (Note: I had to remove the slashes at the beginning and the end.) Could there be some other reason that things aren't working for you? Namespace problems, perhaps?
Don Kirkby
For XML Schema you would have to remove the anchors (`^` and `$`) as well; XSD regexes are implicitly anchored, so those metacharacters aren't supported. But that leaves `default|\d{4}(,\d{4})*`, which the OP already said didn't work, so I don't know what else to suggest.
Alan Moore
@Alan Moore: I was testing it in a console .NET App. I finally need to move it in XSD.
Subhasis
@Don Kirby: You are right. It works great in the site you mentioned. I probably have to look into my app.@Greg: Thanks for your answer.
Subhasis
A: 

Based on replies to the comments, it sounds like you need a regular expression for a pattern restriction in an XSD. According to the XSD spec, this should work:

default|[0-9]{4}(,[0-9]{4})*
jamessan