0

I am trying to write a simple regex that matches all class names in a file. It should match them either with or without a space before the curly bracket.

E.g.

class myClass {...}

Returns ['myClass']

class myClass {....} class Foo{...}

Returns ['myClass', 'foo'].

And so on.

This is what I have so far but it doesnt seem to be working when there is no space befor ethe bracket:

([a-zA-Z_{1}][a-zA-Z0-9_]+)(?=\{)

2 Answers 2

3

Use positive lookbehind and lookahead :

const str = 'class myClass {....} class Foo{...} class Bar   { /* this is a class comment */ }';

const result = str.match(/(?<=class\s)(\w+)(?=\s*{)/g);

console.log(result)

Sign up to request clarification or add additional context in comments.

2 Comments

I just realised that code above work but also matches things that are in a comment. E.G "class Foo{ //this is a class comment}" would return ["Foo", "comment"] how can I uniquely match if they are followed by a curly bracket (or a space before a curly bracket)
@greatTeacherOnizuka i added positive lookahead, check the updated answer.
0

If you want to get not only class declarations but also class instances you might use something like (considering class names follow convention & start from a capital letter):

const sample = `class Foo {};
$a = new Bar;

const myConst = 42;

function thisIsAFunction(){
    console.log(123);
}

class FlowController{}

let laser = new LaserActivator()

var myVar;class NewClass{...};
`;

const classExp = /[\s;][A-Z]\w+?[({\s;]/gm;

sample.match(classExp); //[" Foo ", " Bar;", " FlowController{", " LaserActivator(", " NewClass{"]

Or if you don't want additional characters like spaces, semicolons, etc. to be present, you could use lookahead (something like this):

/[\s;][A-Z]\w+?(?=([\({\s]))/gm;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.