简体   繁体   中英

C# Pattern Matching Failure

Here is the code I am using to find transit numbers of the form RB\\d{4}, SW\\d{4} and S\\d{4}:

Regex transitRegex = new Regex("^(RB|SW?)(<?transit>\\d{4}).*");
Match m1 = transitRegex.Match(transitNumber);
if (m1.Success)
{
    Regex transitRegexNoZeroes = new Regex("0+(<?transitNoZeroes>\\d+)");
    Match m2 = transitRegexNoZeroes.Match(m1.Groups["transit"].Value);
    if (m2.Success)
    {
        transitNumber = m2.Groups["transitNoZeroes"].Value.ToString();
        MessageBox.Show(transitNumber, "Transit Number", MessageBoxButtons.OK);
    }
    else
    {
        transitNumber = m1.Groups["transit"].Value.ToString();
    }
}
else
{
    MessageBox.Show("Could not find transit number in " + transitNumber, "Parsing Error", MessageBoxButtons.OK);
}

However I am failing to match any lines. Here is an example of a line that fails:

RB80720C1XX -  Intermittent COMM lOSS ****CHRONIC**** 

For the life of me I can't figure out what's wrong with the regex. Any advice is appreciated.

Regards.

EDIT: Inner match edited to allow numbers with leading zeroes to still contain zeroes.

Your first pattern is a little off. Try this instead:

@"^(RB|SW?)(?<transit>\d{4})"

Note, the position of the question mark. You can test the pattern here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM