gegy
gegy

Reputation: 87

Regex: Get matching and "not matching" parts of string

I am having a string like this:

%1n--%2n##%12n

I need all matches that match %1n, %2n, %12n and I also need all not matching parts. E.g: -- and ##

My regex pattern is (%\d*n)(?!(%\d*n)*).

I get the matching parts (%1n, ...) and also empty matches from all non-matching parts. But the result for my example should be:

  1. Match: %1n
  2. Match: --
  3. Match: %2n
  4. Match: ##
  5. Match: %12n

Can somebody tell me the correct regex pattern to get my expected result?

Upvotes: 2

Views: 762

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626802

In C#, you may use Regex.Split with a regex wrapped with capturing parentheses to also return all substrings between matches:

var text = "%1n--%2n##%12n";
var result = Regex.Split(text, @"(%\w+)").Where(x => !String.IsNullOrWhiteSpace(x)).ToList();
foreach (var s in result)
    Console.WriteLine(s);

See the C# demo. Output:

%1n
--
%2n
##
%12n

The (%\w+) regex matches and captures into Group 1 a % char and then any one or more word chars. If you only need to match ASCII letters/digits, use (%[A-Za-z0-9]+).

See a VB.NET demo, too:

Dim pattern As String = "(%\w+)"
Dim s As String = "%1n--%2n##%12n"
Dim matches As String() = System.Text.RegularExpressions.Regex.Split(s, pattern)
For Each m As String In matches
    If Not String.IsNullOrEmpty(m) Then
        Console.WriteLine(m)
    End If
Next

Upvotes: 2

Related Questions