C# and Regular expressions

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • hini
    New Member
    • Mar 2007
    • 23

    C# and Regular expressions

    Hi all,

    I have a problem with matching a regular expression.
    the string is multiline, when I replace the newline characters with spaces all goes fine.
    is there another way to do it without replacing anything ?

    let's say the string is:
    item1=102
    item2=345
    ...
    lastval=1234556


    what I want to do is to read the values of item2 and lastval and store them in a couple of variables.

    and I used the following code :

    Code:
    using (StreamReader sr = new StreamReader(File.OpenRead("48A8A1B3.ERR")))
                {
                    string s = sr.ReadToEnd();// here I read the file
                    s = s.Replace("\n", " "); // here I replace newlines with spaces, this is what I want to get rid of
                    Regex reg = new Regex(@"item2=(?<RouteName>\w*)(.*)lastval=(?<PhoneNumber>\w*)");
                    if (reg.Matches(s).Count > 0)
                    {
    
                        Match m = reg.Matches(s)[0];
    
                        string RouteName = m.Result("${RouteName}");
                        string PhoneNumber = m.Result("${PhoneNumber}");
                        MessageBox.Show(RouteName);
                        MessageBox.Show(PhoneNumber);
                    }
                    
                }
    thx for helping ;)
  • DonBytes
    New Member
    • Aug 2008
    • 25

    #2
    Change:
    Code:
    Regex reg = new Regex(@"item2=(?<RouteName>\w*)(.*)lastval=(?<PhoneNumber>\w*)");
    Into:
    Code:
    Regex reg = new Regex(@"item2=(?<RouteName>\w*)(.*)lastval=(?<PhoneNumber>\w*)", RegexOptions.Singleline);
    And you won't have to replace anything.

    Comment

    • hini
      New Member
      • Mar 2007
      • 23

      #3
      thanks a lot !
      I tried to use the multiline option because I thought it was the correct one,
      never thought it is exactly the opposite :)

      Comment

      Working...