Yu Taylor
Yu Taylor

Reputation: 63

Find all matched string by regex

I have a combined command string like below, and each command length is not fixed, minimum is 22, maximum is 240:

5B01CA0F00000241FF0201040F325D5B01CA0F00000241FF0201040F335D6B01FF0000000010FF01FF0000000F6D5B01CA0F00000241FF0201040F345D5B01CA0F00000241FF0201040F355D6B01FF0000000010FF01FF0000000F6D

I want to extract command like 5B....5D or 6B....6D, so the expected result is :

5B01CA0F00000241FF0201040F325D

5B01CA0F00000241FF0201040F335D

6B01FF0000000010FF01FF0000000F6D

5B01CA0F00000241FF0201040F345D

5B01CA0F00000241FF0201040F355D

6B01FF0000000010FF01FF0000000F6D

I used regex pattern like

5B[0-9a-fA-F]{22,240}5D or (?<=5B)([0-9a-fA-F]{22,240})(?=5D)

Only one matched, can anyone help me for this?

string regexPattern = "(?<=5B)([0-9a-fA-F]{22,240})(?=5D)";
string command = txtRegexCmd.Text.Trim();
MatchCollection matchedResults = Regex.Matches(command, regexPattern, RegexOptions.IgnoreCase);
string matchedCmd = string.Empty;
foreach (Match matchResult in matchedResults)
{
    matchedCmd += matchResult.Value + ",\r\n";
}
MessageBox.Show(matchedCmd);

Upvotes: 2

Views: 75

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You may match them using

([65])B.*?\1D

See the .NET regex demo and the Regulex graph:

enter image description here

The ([65])B.*?\1D pattern captures into Group 1 a 5 or 6 digit, then matches B, then any 0+ chars other than a newline as few as possible up to the first occurrence of the same char as captured in Group 1 followed with D.

C# code:

var results = Regex.Matches(s, @"([65])B.*?\1D")
            .Cast<Match>()
            .Select(x => x.Value)
            .ToList();

enter image description here

If you want to split after each 5D or 6D, just use

var results = Regex.Split(s, @"(?!$)(?<=[56]D)");

Here, (?!$)(?<=[56]D) matches a location that is not the string end and it must be immediately preceded with 5D or 6D. See this regex demo.

enter image description here

Upvotes: 1

Rahul
Rahul

Reputation: 2738

You can split string on characters as suggested by Emma. If you must use regex, you can use lookbehind like this.

Regex: (?<=5D|6D)

Explanation: It will search for zero width after 5D and 6D. Then you can add newline character as replacement.

Demo on Regex101

Upvotes: 1

Emma
Emma

Reputation: 27723

This RegEx might help you to separate your string into desired pieces that you wish.

(?:5|6)B[0-9a-fA-F]{26,28}(?:5|6)D

It would create two left and right boundaries for each desired output.

RegEx

Upvotes: 0

Related Questions