C# WPF RegEx - only numbers and charactes in a range

Markus Freitag 3,786 Reputation points
2020-11-19T14:42:20.323+00:00

Hello,

    string text = "[>[RS]06[GS]PTVK1281257[GS]21PR4A[GS]11D201632[GS]Q60[GS]18VLMDM5[GS]1TAFJH0010-1[GS]13E5a[GS]1PW12R789B[GS]4LCN[GS][RS][EOT]]";  
            const string regExprLPLayout = @"\b1P([A-Z0-9]{0,55})\b";              
  
            foreach (Match m in Regex.Matches(text, regExprLPLayout))  
            {  
                System.Diagnostics.Trace.WriteLine($"Found: {m.Value}, Group1: {m.Groups[1].Value}");  
            }  

41151-1.png

1PW12R789B

Prefix is 1P
Case 1:
All chars after 1P -> works. @"\b1P([A-Z0-9]{0,55})\b";
Case 2:
A range 'R789' after 1P -> works. @"\b1P([A-Z0-9]{3,4})\b"; works not

How can I reach the goal?

Is there a way to filter out all key/values with a RegEx? If yes how?
11D201632
PTVK1281257

Key/Value or Prefix/value

Thanks.

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,778 questions
{count} votes

Accepted answer
  1. Viorel 117.6K Reputation points
    2020-11-20T07:02:58.203+00:00

    If the order is not important and there are no duplicates, then check an example that puts the results into dictionary:

    string text = "[>[RS]06[GS]PTVK1281257[GS]21PR4A[GS]11D201632[GS]Q60[GS]18VLMDM5[GS]1TAFJH0010-1[GS]13E5a[GS]1PW12R789B[GS]4LCN[GS][RS][EOT]]";
    
    Dictionary<string, string> results =
     Regex.Matches( text, @"(?i)](\d*[A-Z])(.+?)\[" ).Cast<Match>( ).ToDictionary( m => m.Groups[1].Value, m => m.Groups[2].Value );
    
    Console.WriteLine( text );
    
    foreach( var p in results )
    {
     Console.WriteLine( "Key: {0,-10} Value: {1}", p.Key, p.Value );
    }
    
    /*
    Results:
    
    Key: P          Value: TVK1281257
    Key: 21P        Value: R4A
    Key: 11D        Value: 201632
    Key: Q          Value: 60
    Key: 18V        Value: LMDM5
    Key: 1T         Value: AFJH0010-1
    Key: 13E        Value: 5a
    Key: 1P         Value: W12R789B
    Key: 4L         Value: CN
    */
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.