Reputation: 136144
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
type MyClass inherits SomeClass,SomeOtherClass implements Node
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.
Upvotes: 0
Views: 1777
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 charsJS 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
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