Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, I'm hoping somebody can kickstart my brain on Regular expressions. I have read The 30 Minute Regex Tutorial[^] , but I'm still stuck.

My requirement is to take a string like this:

public abc.def.ghi.MYDATA1 MYDATA2;

and recognise it by:

1. it starts with public
2. it contains .def.ghi, but abc may differ.

I need to extract:

1. MYDATA1
2. MYDATA2

So:

\bpublic\b finds the word public : \bpublic\b
.* will cover the next unknown characters : \bpublic\b.*
def.ghi. is the next known (this could be wrong from here : \bpublic\b.*(def\.ghi\.)

And now I have hit a block, the tester at regex Planet[^] tells me I have already gone wrong.

Help!
Posted

To parse source code, you should:

  • treat the whole file as "singleline", i.e. the Regex should not treat new lines as special characters
  • allow whiespaces between language tokens (all these \s* look a bit ugly, but is necessary to catch all entries)
  • carefully tokenize, e.g. if you only expect not escaped identifier[^], use \w+, otherwise you need to be more creative ;-)


C#
string text = "..."; // file content
                  // public   Word   .   def    .   ghi    .   Type    Name    ;
string pattern = @"\bpublic\s+\w+\s*\.\s*def\s*\.\s*ghi\s*\.\s*(\w+)\s+(\w+)\s*;";
foreach(Match m in Regex.Matches(text, pattern, RegexOptions.Singleline))
{
    Console.WriteLine("1. {0}", m.Groups[1].Value);
    Console.WriteLine("2. {0}", m.Groups[2].Value);
}


If you have multiple "Word." layers (e.g. A.B.C.def.ghi...), you may extend the pattern as follows:
C#
string pattern = @"\bpublic\s+(?:\w+\s*\.\s*)+def\s*\.\s*ghi\s*\.\s*(\w+)\s+(\w+)\s*;";


Cheers
Andi
 
Share this answer
 
v5
How about something like this?

public\s+(?'space'\w+\.\w+\.\w+)\.(?'type'\w+)\s+(?'name'\w+);

I prefer to use named capture groups to extract pieces.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900