views:

61

answers:

3

I am not very good in regex so I'm looking for help. I need to fetch content between . and {.

Example:

  .aaa  { }
  .bbb {}
   ccc {}
   ddd {}
   eee {}

I.e. aaa and bbb in a string. This data can change so I want to use a regex for this. Thanks.

Spaces are allowed and new lines are allowed. This is a simple text file.

+5  A: 
(?<=\.)[^{]*(?=\{)

will match everything between . and {.

Explanation:

(?<=\.) asserts that the preceding character is a dot. [^{]* matches zero or more characters, anything except {. (?=\{) asserts that the following character is a {.

To iterate over all matches in a string (C#):

Regex regexObj = new Regex(@"(?<=\.)[^{]*(?=\{)");
Match matchResults = regexObj.Match(subjectString);
while (matchResults.Success) {
    // matched text: matchResults.Value
    // match start: matchResults.Index
    // match length: matchResults.Length
    matchResults = matchResults.NextMatch();
} 
Tim Pietzcker
as i said i just want to selct data between . { i dont wanna include ddd and ccc as they are not having . at the starting
Sangram
Yes, and this is what this regex does. Is there a problem?
Tim Pietzcker
man its working great..thanx a lot
Sangram
A: 

Here is a simpler one:

\.([^{]*)\{

If you don’t want the spaces included in the results, use this:

\.\s*([^{]*?)\s*\{

Example of use:

foreach (Match match in Regex.Matches(input, @"\.\s*([^{]*?)\s*\{"))
    Console.WriteLine(match.Groups[1].Value);

This example prints “aaa” and “bbb” given your input.

Timwi
+1  A: 

hey,

i finally managed to take all data between . and { and make a list.Using REGEX help from stackoverflow.i have replaced all \n,\r,spaces bye replacing it with blank. I have changed it a bit according to my needs. This is my final fuction which has worked fantastically.

public static void MakeList(string s)
        {

            string PATTERN = @"(?<=\.)[^{]*(?=\{)";

            s = s.Replace("\r", "").Replace("\n", "").Replace(" ","");
            var matches = Regex.Matches(s, PATTERN);
            var styleList = new List<string>();


            for (int i = 0; i < matches.Count; i++)
            {

                styleList.Add(matches[i].ToString());
            }
        }

thanx to all.

Sangram