0

I am trying to write a Java Script regex to match if a string contains only allowed characters in following manner -

  1. String shall have only 0, 1, x or comma (,) in it.
  2. Each number (0, 1 or "x") shall be separated by a comma (,)
  3. There shall be at least one comma separated value (i.e. "0,1" or "0,x,1")
  4. The comma shall always be surrounded by numbers or "x" (i.e. "," or ",0" is invalid )

Is it possible to write a regex for this condition? I am able to do it using java script string split but that does not appear elegant to me. Hope someone could help come up with a regex for above condition.

1
  • SomeKittens - I thought it was not necessary to show how I tried in this case as the split functionality is pretty straight forward way that I said I tried. Split it, loop through it and check. Since I was looking for regex equivalent and that was not directly related to split I did not include the code. Commented Jul 17, 2012 at 17:14

1 Answer 1

3

Although I agree with @SomeKittens that you should show what you tried, you at least provided a fairly detailed spec. Based on my understanding of it, you can use something like this:

var isValid = /^(?:[01x],)+[01x]$/.test(str);

That matches any of these:

  • 0,1
  • 0,1,1
  • 0,x,0,0

And none of these:

  • 0
  • ,
  • 0,
  • 0,1,
  • ,1
  • 0,,1
  • 0,X (uppercase X)

If you want to allow matching uppercase Xs in addition to lowercase, add the /i flag to the regex for case insensitive matching.

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

1 Comment

Thank you for the regex. I normally always do include the code but in this case I worked on a java script split based solution which I thought would not add anything to regex discussion. I will add ignore case in my regex string as well. Thank you for your quick help on this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.