简体   繁体   中英

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);

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

You may match them using

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

See the .NET regex demo and the Regulex graph:

在此输入图像描述

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();

在此输入图像描述

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 .

在此输入图像描述

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.

正则表达式

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM