Tiago Tiago - 28 days ago 4x
Objective-C Question

Parse all NS* variables in source using regex

I'm trying to extract the names of all variables within an objective-c .m file. I thought regex might be a good way to do this. Let's say I have something like this in my source:

- (void)testMethod:(NSString*)param1Name param2:(NSString*)param2Name{
NSxxxxx *xxxx = @"something";
NSString *test2 = @"test";
NSArray *array;

Ideally the output I'm looking for, is something like this:

Is this doable with regex? I think one regex might be enough to extract all lines with a word that starts with NS when the next word starts with *.

Edit: I have this so far:


Problem with this is that it matches the type of the var, not the var name:


How can I get this to match the word after the asterisk?


Since you want to match specific occurrences of NS* variables (those at the start of the lines), you may use

(?m)^[ \t]*NS\w+\s*\*\s*(\w+)

See this regex demo

The value you need will be inside Group 1.


  • (?m) - Multiline option ON to allow ^ to match the start of a line, not string
  • ^ - start of a line
  • [ \t]* - zero or more spaces/tabs
  • NS - a literal text NS
  • \w+ - 1+ word chars (letters, digits or underscores)
  • \s* - 0+ whitespaces
  • \* - an asterisk
  • \s* - zero or more whitespaces
  • (\w+) - Group 1 - 1+ word chars.