Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex match lines that are not commented

So I have a string read from a JavaScript file, that will have:

...
require('some/path/to/file.less');
...
// require('some/path/to/file.less');
...

I'm using this reg-ex:

requireRegExp = /require(\ +)?\((\ +)?['"](.+)?['"](\ +)?\)\;?/g

To catch all those lines. However, I need to filter out the ones that are commented.

So when I run

while( match = requireRegExp.exec(str) ){
...
}

I will only get a match for the uncommented line that starts with require...

like image 795
André Alçada Padez Avatar asked Mar 15 '23 23:03

André Alçada Padez


1 Answers

regequireRegExp = /^\s*require\('([^']+)'\);/gm

Explanation:

^ assert position at start of a line

\s* checks for a whitespace character 0 ... many times

require matches the word require

\( matches the character (

' matches the character '

([^']+)matches anything that isnt a ' 1 ... many times

Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed

' matches the character ' literally

\) matches the character ) literally

; matches the character ; literally

g modifier: global. All matches (don't return on first match)

m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)

EDIT

Apparently you wanted to get the path in a group so I edited my answer to better respond to your question.

Here is the example:

https://regex101.com/r/kQ0lY8/3

like image 173
Alex Avatar answered Mar 23 '23 14:03

Alex