正则表达式 - 从[[A] 16和5以及A [20]和15“获得[A] 16,5,A [20],15

时间:2012-04-26 07:54:40

标签: c# regex expression

我有一个这样的字符串 - "[A]16 and 5th and A[20] and 15"

我需要取值[A]165A[20]15。 (数字和[A],如果存在的话)

我正在使用C#。

 string[] numbers = Regex.Split("[A]16 and 5th and [A]20 and 15", @"\D+");

下面的代码只给我数字。但我还需要[A]字体(如果存在)。

拜托,能帮帮我吗。

4 个答案:

答案 0 :(得分:1)

更通用的模式可能是:

@"\[[A-Z]][0-9]+|[A-Z]\[[0-9]+]|[0-9]+"



[[A-Z]][0-9]       - matches [Letter from A-Z]Number          example: [A]10
or |[A-Z]\[[0-9]+] - matches Letter from A-Z[Number]          example: A[10]
or |[0-9]+         - matches Numers from 1-N                  example: 5, or 15

答案 1 :(得分:0)

如果只有@"(\[A\])?\d+" s,请使用此模式:[A] 如果您还有[B][C] ...您可以使用此模式:@"(\[[A-Z]\])?\d+"

答案 2 :(得分:0)

您可以使用此模式:

string lordcheeto = @".*?(\[A\]\d+|\d+|A\[\d+\]).*?";

它还会根据你想要的比赛修剪垃圾。虽然,由于Split的工作方式,数组中会有空字符串。至于看似必要的一般情况,你可以使用:

string lordcheeto = @".*?(\[[A-Z]\]\d+|\d+|[A-Z]\[\d+\]).*?";

<强>代码

using System;
using System.Text.RegularExpressions;

namespace RegExIssues
{
    class Program
    {
        static void Main(string[] args)
        {
            // Properly escaped to capture matches.
            string lordcheeto = @".*?(\[A\]\d+|\d+|A\[\d+\]).*?";
            string input = "[A]16 and 5th and A[20] and 15";

            executePattern("lordcheeto's", input, lordcheeto);

            Console.ReadLine();
        }

        static void executePattern(string version, string input, string pattern)
        {
            // Avoiding repitition for this example.
            Console.WriteLine("Using {0} pattern:", version);

            // Needs to be trimmed.
            var result = Regex.Split(input.Trim(), pattern);

            // Pipe included to highlight empty strings.
            foreach (var m in result)
                Console.WriteLine("|{0}", m);

            // Extra space.
            Console.WriteLine();
            Console.WriteLine();
        }
    }
}

<强>测试

http://goo.gl/VNqpp

<强>输出

Using lordcheeto's pattern:
|
|[A]16
|
|5
|
|A[20]
|
|15
|

<强>评论

如果你需要更多或者其他字符串中断,请告诉我,我可以修改它。

答案 3 :(得分:0)

试试这个:

(\[[A-Z]\][0-9]+)|([A-Z]\[[0-9]+\])|([0-9]+)

演示:

http://regexr.com?30p8v