a way to ignore the rest of a string after a certain character??

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • USBZ0r
    New Member
    • Mar 2009
    • 20

    a way to ignore the rest of a string after a certain character??

    Hi guys, is there anything i can do to only read a certain part of a string, im reading an IP, but the IP contains the port like 127.0.0.1:80, but i dont want to include the ":80". i cant tell it how long the string is because the IP's change and the lengh varies. so i need to ignore anything after " : ".

    Thanks
  • PRR
    Recognized Expert Contributor
    • Dec 2007
    • 750

    #2
    you could use indexof and substring method (for short strings)...
    Code:
    string filterChar = ":";
                    string myLongString = @"Some where rrr :  sdfsdf";
                    int inde = myLongString.IndexOf(":");
                    if (inde > 0)// or not equal to -1 will do 
                    {
                        string myShortString = myLongString.Substring(0, inde - 1);
                    }
    A better approach would be regular expression for larger string ...

    Comment

    • USBZ0r
      New Member
      • Mar 2009
      • 20

      #3
      Thanks deepblue, appreciate it!

      Comment

      • jg007
        Contributor
        • Mar 2008
        • 283

        #4
        only just learning regex's but this seems to work , I am getting the value from textbox1 to test it

        Code:
        string RegexMatchString = @"(?<IP>\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})";
                    Regex testr = new Regex(RegexMatchString);
                    Match matx = testr.Match(textBox1.Text);
                    MessageBox.Show(matx.Groups["IP"].Value);

        Comment

        • jg007
          Contributor
          • Mar 2008
          • 283

          #5
          a bit simpler -

          Code:
                      string RegexMatchString = @"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}";
                      Regex testr = new Regex(RegexMatchString);
                      MessageBox.Show(testr.Match(textBox1.Text).Value) ;

          Comment

          Working...