R4D4
R4D4

Reputation: 1402

Reasonably simple regular expression not finding any results

I'm trying to construct a regular expression that would extract the name of the structure, although I'm not finding anything with it. The steps I'm working through are:

  1. Look for the string 'public struct'.
  2. Find all characters A-Z a-z one or more times and group them.
  3. Then look for line feed, carrige return or any other character one or more times (I think this would account for the opening curly bracket and the possibility of any spaces).
  4. Finally look for a }

/

public struct ABC{
    int a;
    int b;
}

public struct DEF {
    ulong d;
    string e;
}

Regex:
    public struct ([A-Za-z]+)[{|\r|\n|.]+}

Should give:
    ABC
    DEF

Why is the regular expression not finding anything?

Upvotes: 1

Views: 39

Answers (2)

Bogdan Emil Mariesan
Bogdan Emil Mariesan

Reputation: 5647

To extract only the 'ABC' part you would require positive lookeahead in your regex. A simple solution for this would be:

(?<=(public struct ))[\w]+

So with your given example it will extract only:

  • ABC
  • DEF

EDIT: Here is a link with the working example:

http://gskinner.com/RegExr/?319vk

Upvotes: 1

Qtax
Qtax

Reputation: 33908

Because the body contains more than what can be matched by [{|\r|\n|.]+.

If you only want the name you can just use:

public struct (\w+)\s*{

[{|\r|\n|.]+ is the same as [{\r\n.|]+ (brackets are a character class, not a group), you probably meant [^}]+.

Upvotes: 2

Related Questions