Got more questions? Find advice on: ASP | SQL | XML | Windows
in Search
Welcome to RegexAdvice Sign in | Join | Help

Omit optional final question mark from capture

Last post 10-06-2008, 12:50 PM by Mick280. 3 replies.
Sort Posts: Previous Next
  •  10-03-2008, 3:51 PM 46868

    Omit optional final question mark from capture

    I am working with C# and .NET. The strings I am looking at have are text, possibly with numbers in various places and an optional final question mark.
    If there is a number at the end of the string or before the question mark I need to capture it, parse it, and then remove it from the string. Here is my code:

    Match trailingNumber = Regex.Match(command, @"\d+(?:\??)$");
    if (!String.IsNullOrEmpty(trailingNumber.Value) && int.TryParse(trailingNumber.Value, out index))
        command = Regex.Replace(command, @"\d+(\??)$", "$1");

    The problem is that the non-capturing group is capturing the '?' in a string such as "3abc99?" causing the match to be "99?" instead of "99". In the replace command I am able to deal with this but how can I prevent the initial match from including the question mark?
    Thanks!

  •  10-03-2008, 9:36 PM 46869 in reply to 46868

    Re: Omit optional final question mark from capture

    Please provide some sample content and show what you would like to match within that content.


  •  10-05-2008, 2:40 PM 46896 in reply to 46868

    Re: Omit optional final question mark from capture

    I think you are confusing the terminology of "capturing" with the idea of a regex matching. Everything that can be matched is returned the match. Capturing and non-capturing groups have no effect on that. For an overview on using grouping http://regexadvice.com/blogs/mash/archive/2007/06/01/You_2700_ve-got-your-sub_2D00_matches-in-my-matches.aspx

    Michael

    "In theory, theory and practice are the same. In practice, they are not."
    Albert Einstein
  •  10-06-2008, 12:50 PM 46921 in reply to 46896

    Re: Omit optional final question mark from capture - issue resolved!

    ddrudik - The sample content is there: input "3abc99?" or "3abc99", desired output "99".

    mash - Thanks, that is exactly what the problem was - I should have been using Regex.Matches instead of Regex.Match, and then looked at the groups. The revised code that works is:

    MatchCollection trailingNumbers = Regex.Matches(command, @"(\d+)(?:\??)$");    // only capture the number
    if (trailingNumbers.Count>0) {
        int.TryParse(trailingNumbers[0].Groups[ 1 ].Value, out index);
        command = Regex.Replace(command, @"\d+(\??)$", "$1");
    }

View as RSS news feed in XML