c# - 捕获可变长度的子串引用号

标签 c# regex

对于一个小问题,我有一个简单的解决方案,但作为一个开发新手,我总是想学习更正确/更好的方法来做某事。此刻,我得到一个看起来或多或少像这样的字符串......

Some Random Text, Reference Number: Supp-1234 and some more random text...

现在,如果我们假设这种情况并且我们只想获取引用号的数字部分,我们可以这样做...

int firstCharacter = mystring.IndexOf("Supp-", StringComparison.InvariantCultureIgnoreCase);
myIssueId = firstCharacter != -1 ? mailItem.Subject.Substring(firstCharacter + 5, 4) : "";

但是现在,假设我们得到一个引用号 Supp-12345,现在这行不通了。你可以尝试这样的事情......

int firstCharacter = mystring.IndexOf("Supp-", StringComparison.InvariantCultureIgnoreCase);
if (firstCharacter != -1)
{
    string temp = mystring.Substring(firstCharacter + 5, 5);
    try
    {
        int x = Convert.ToInt32(temp); // to ensure it is indeed a number
    }
    catch (Exception)
    {
        temp = mystring.Substring(firstCharacter + 5, 4); // it is 4 digits, not 5
    }
    myIssueId = temp;
}

现在我的问题是这个。我该如何改进这段代码?它有点太乱了,我不喜欢。任何想法将不胜感激。

最佳答案

您正在寻找一些以字符串“Supp-”开头的数字。这可以翻译成正则表达式,如

(<=Supp-)\d+

您可以像 myIssueId = Regex.Match(input, "(<=Supp-)\d+").Value 那样使用它.

关于c# - 捕获可变长度的子串引用号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18186442/

相关文章:

c# - C# MVC4.0 中的有效 Math.Random

c# - 优化 LINQ-to-SQL 查询

Python:动态构建正则表达式的最佳实践

regex - Git 搜索内容中包含特定 unicode 字符的提交

regex - GROK 正则表达式捕获组不匹配

c# - 使用数据库优先方法时覆盖或替换默认构造函数

c# - 在同一行 2 上对齐 html 输入

Java:如何在运行时使用可变参数正确构造正则表达式

c# - 显示 'saved' 标签 2 秒然后在 c# asp.net 中隐藏

css - 在 Sublime 中搜索所有字体系列 : not preceded by an opening comment 的正则表达式