Need To build a REGEX to be placed in javascript

Viewed 28

MY Regex :

/^[\s]*(\'[a-zA-Z0-9_:\.\-\s\\\/\(\)\&\>\<]+(\,+\s*[a-zA-Z0-9_:\.\-\s\\\/\(\)\&\>\<]+)*\'[\s\,]*)*$/

I want it to Validate ::

'A','B,C','D','E,F','G','H'....... // like wise no specific pattern

Here, 'A' can be a word or sentence and same goes for other Letters mentioned above.

Invalid cases ::

A','B'    // Missing single quote
'A''B'    // Missing comma
A',B'     // Missing single quote
'A','B    // Missing single quote 
'A','B',  // Extra comma
'A',,'B'  // Double comma
,'A','B'  // Comma at beginning

Some of these invalid cases are not being catched by my REGEX. What should I change in my regex?

I have tested it on https://regex101.com/

1 Answers

You may use this regex to invalidate all strings you've shown in your question:

/^\s*'[^']*'(?:,'[^']*')*\s*$/gm

Assumption is that there is no escaping of single quotes in your input.

RegEx Demo

RegEx Details;

  • ^: Start
  • \s*: Match 0 or more whitespaces
  • '[^']*': Match a single quoted string
  • (?:,'[^']*')*: Match comma followed by a single quoted string. Math 0 or more of this group
  • \s*: Match 0 or more whitespaces
  • $: End

If escaped single quotes i.e. \' can be part of input then you may use:

/^\s*'(?:[^'\\]|\\.)*'(?:,'(?:[^'\\]|\\.)*')*\s*$/gm
Related