C#正则表达式匹配字符串末尾的数字

时间:2022-09-19 17:57:59

I have a string that ends with _[a number] e.g. _1 _12 etc etc.

我有一个以_ [数字]结尾的字符串,例如_1 _12等

I'm looking for a regular expression to pull out this number

我正在寻找一个正则表达式来提取这个数字

2 个解决方案

#1


Try this:

(\d+)$

Here is an example of how to use it:

以下是如何使用它的示例:

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        Regex regex = new Regex(@"(\d+)$", 
            RegexOptions.Compiled | 
            RegexOptions.CultureInvariant);

        Match match = regex.Match("_1_12");

        if (match.Success)
            Console.WriteLine(match.Groups[1].Value);
    }
}

#2


Try

_(\d+)$

#1


Try this:

(\d+)$

Here is an example of how to use it:

以下是如何使用它的示例:

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        Regex regex = new Regex(@"(\d+)$", 
            RegexOptions.Compiled | 
            RegexOptions.CultureInvariant);

        Match match = regex.Match("_1_12");

        if (match.Success)
            Console.WriteLine(match.Groups[1].Value);
    }
}

#2


Try

_(\d+)$