Pankaj Parkar
Pankaj Parkar

Reputation: 136144

Regex for comma separated string with/without spaces

I want to create a Regex where I want to extract string that is satisfying pattern.

Input string can appear in below two possible ways

  1. type MyClass inherits SomeClass,SomeOtherClass implements Node
  2. type MyClass inherits SomeClass, SomeOtherClass implements Node

Note: implements word can be anything like extend/union/intersection etc.

The regex should extract "inherits SomeClass, SomeOtherClass" string from the above input string.

I tried multiple SO answers and different online sources, but can't get success in the same. I used /inherits\s(.*?)\s/mg which only works for 1st case.

What would be regex to satisfy both the cases? Help would be appreciate.

JSFiddle here

Upvotes: 0

Views: 1777

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626861

You may use

/inherits\s+\w+(?:\s*,\s*\w+)*/g

See the regex demo.

Details

  • inherits - a literal substring
  • \s+ - 1+ whitespaces
  • \w+ - 1+ word chars (letters,digits or underscores)
  • (?:\s*,\s*\w+)* - zero or more (*) occurrences of:
    • \s*,\s* - a , enclosed with 0+ whitespace chars
    • \w+ - 1+ word chars

JS demo:

var regex = /inherits\s+\w+(?:\s*,\s*\w+)*/g;

var input1 = "type MyClass inherits SomeClass,SomeOtherClass implements Node";
var input2 = "type MyClass inherits SomeClass, SomeOtherClass implements Node";

var result1 = input1.match(regex);
var result2 = input2.match(regex);

document.write("result 1: "+ result1);
document.write("<br>")
document.write("\n result 2: "+ result2);

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68393

Check if the string is followed by implements

var regex = /inherits\s+(.*)\s+(?=implements?)/mg;

var str1 = "type MyClass inherits SomeClass,SomeOtherClass implements Node";
var str2 = "type MyClass inherits SomeClass, SomeOtherClass implements Node";

str1.match( regex ) //["inherits SomeClass,SomeOtherClass "]

str2.match( regex ) //["inherits SomeClass, SomeOtherClass "]

Upvotes: 1

Related Questions