【问题标题】:Return Group From Regex, not the whole line [duplicate]从正则表达式返回组,而不是整行[重复]
【发布时间】:2013-01-15 20:34:39
【问题描述】:

可能重复:
Regex matching too much

测试字符串:

[TA:1010100][FN:AmplifySignal][IP:(Factor|System.Double|"1.5")(Source|System.String|"Sourcetest")(Destination|System.String|"DestTest")]

此字符串的一般格式分为 3 组:

  • group1 => "[TA:" + 1 或 0 重复 + "]"
  • group2 => "[FN:" + A-Z 或 a-z + "]"
  • group3 => "[IP:" + (.*) + "]"

我已经尝试了许多正则表达式的变体,可以让整个测试字符串返回或什么都不返回...我可以弄清楚如何实际分割它并只返回子字符串。

尝试过的模式包括但不限于:

  • @"^.*$"
  • @"^[.*].*$"
  • @"^(\[.*\])(.*)$"
  • @"^(\[.*\])(\[.*\])(\[.*\])$"
  • @"^(\[TA{[10],}\])(\[.*\])(\[.*\])$" ...等等。

调用代码:

BindingList<Tuple<bool[], IFactory>> Recipe = new BindingList<Tuple<bool[], IFactory>>();

var amp = new Factory.AmplifySignal();
amp.Destination = "DestTest";
amp.Source = "Sourcetest";
amp.Factor = 1.5;
bool[] Ts = new bool[] { true, false, true, false, true, false, false };

var CI = new CompactInstruction(Ts, amp.GetFactoryKey(), amp.GetProperties());

string TestString = CI.ToString();
Console.WriteLine(TestString);

string pattern = @"^(\[.*\])?"; //Have been adjusting in debug mode
while (true)
{
    try
    {
        Match Result = Regex.Match(TestString, pattern, RegexOptions.IgnoreCase);
        if (Result.Success)
        {
            for (int i = 0; i < Result.Groups.Count; i++)
            {
                Console.WriteLine("G{0} - \r\n\t{1}", i, Result.Groups[i]);                            
            }
        }
    }
    catch { }
}

【问题讨论】:

标签: c# regex


【解决方案1】:

测试

[TA:1010100][FN:AmplifySignal][IP:(Factor|System.Double|"1.5")(Source|System.String|"Sourcetest")(Destination|System.String|"DestTest")]

模式

string pattern = @"^(\[.*?\])?(\[.*?\])?(\[.*?\])?$";

输出:

G0 - 
    [TA:1010100][FN:AmplifySignal][IP:(Factor|System.Double|"1.5")(Source|System.String|"Sourcetest")(Destination|System.String|"DestTest")]
G1 - 
    [TA:1010100]
G2 - 
    [FN:AmplifySignal]
G3 - 
    [IP:(Factor|System.Double|"1.5")(Source|System.String|"Sourcetest")(Destination|System.String|"DestTest")]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-06
    • 2018-04-15
    • 2020-09-04
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    相关资源
    最近更新 更多