0

I want to check if a given string meets the required format in javascript. I want to use regex to do it, but I can not write the proper regex.

The required format is like optiona;optionb;optionc, and there will be at least one ; in the string to separate the option, each option will have at least three characters.

The options value can not contain ; but can contain empty space inside it (not in the beginning or end)

below is some example of it:

var str1="aaa;BBC;ccc";//valid
var str2=";aaa;bbb;ccc";//invalid, because it starts with ;
var str3="aaa;bbb;ccc;";//invalid, because it ends with ;
var str4="aaa;bbb;ccc;ddd"; //valid
var str5="aaa;b;ccc";//invalid, because the second option is b, the length is less than 3
var str5="aaa;bbb;;ccc";//invalid, because it has duplicate ;
var str6="aa a;bbb;ccc";//valid
var str7="aaa ;bbb;ccc";//invalid,empty space in the end of first option
var str8=" aaa;bbb;ccc";//invalid,empty space in the begin the first option
var str9="aaa;bb b;ccc;ddd";//valid
var str10="aaa;bbb ;ccc;ddd";//invalid,empty space in the end of second option
var11="aaa;bbb";//valid

How to use regex to check it. Can anyone help me? Thanks in advance!

Karen Grigoryan
  • 5,234
  • 2
  • 21
  • 35
flyingfox
  • 13,414
  • 3
  • 24
  • 39

1 Answers1

0

The only tricky part to this problem is checking length while following other rules. So an option with 3 characters long would be matched with:

\w[ \w]+\w

Here is the regex:

^\w[ \w]+\w(;\w[ \w]+\w)+$
 ^^^^^^^^^^  ^^^^^^^^^^

Beginning and end of input string anchors, ^ and $, should be used. I used a capturing group construct but you may want to change it to a non-capturing one.

Live demo

revo
  • 47,783
  • 14
  • 74
  • 117