【问题标题】:Filter Number from string in c#从C#中的字符串中过滤数字
【发布时间】:2020-09-09 05:06:23
【问题描述】:

我需要过滤字符串中特定单词后的数字。例如

(CaseId : 200908005485) 测试 WTest3 ==> 需要编号200908005485

[CaseId : 200908005486] 测试 WTest ==> 需要编号 200908005486

注意:CaseId 可以在字符串中的任何位置。

    private string GetObjectIDFromSubjectWithCustomExpression(ItemType itemType, string subject, string expression)
    {
        if (string.IsNullOrEmpty(expression))
            return null;
        //[Case ID:678878],   [Case ID:#ObjectId#]

        string exp = GetFieldNameFromExpression(expression);

        var pattern = expression.Replace("#" + exp + "#", "[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]");
        if (subject.Contains('('))
        {
            pattern = expression.Replace("[", "(").Replace("]", ")").Replace("#" + exp + "#", "[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]");
            pattern = pattern.TrimEnd();
        }
        var rx = new Regex(pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        if (rx.IsMatch(subject))
        {
            var collection = rx.Matches(subject);
            if (collection.Count > 0)
            {
                var matchedstring = collection[collection.Count - 1].Value;
                Regex re = new Regex(@"\d+");
                Match m = re.Match(matchedstring);
                if (m.Success && !string.IsNullOrEmpty(m.Value))
                {
                    exp = m.Value;
                    return exp;
                }
            }
        }

        return null;
    }

试过了,效果很好,但我想要一种更有效的方法。

【问题讨论】:

  • :作为分隔符分割字符串怎么样,比如expression.Split(":")[1]
  • 请定义“更高效”?在什么方面有效?
  • @FranzGleichmann 高效,它可以是 6 位数字或 13 位数字。它可能会有所不同。
  • @that_guy_jrb 这绝不是效率,而是增加功能的特定方式。
  • 另外,this page of the manual 可能会回答你的问题

标签: c# regex string


【解决方案1】:

CaseId : 200908005485) 测试 WTest3 ==> 需要编号 200908005485

[CaseId : 200908005486] 测试 WTest ==> 需要编号 200908005486

要从上面的行中获取 CaseId,请创建一个像“CaseId : ([0-9]*)”这样的正则表达式模式。这里 () 有助于获取子匹配组,即匹配对象中的数字。

这里 [0-9] 匹配 0-9 之间的任意数字,* 使其匹配 n 次。

如果数字是特定长度的,只需将模式更改为“CaseId : ([0-9]{lenght of the number})”。这里的 {} 有助于将数字仅匹配到指定的长度,如果数字超过指定的长度,则正则表达式匹配将忽略剩余的数字。

使用此网站测试和了解更多关于正则表达式https://regex101.com/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多