简体   繁体   中英

How can I use RegEx (Or Should I) to extract a string between the starting string '__' and ending with '__' or 'nothing'

RegEx has always confused me.

I have a string like this:

  IDE\DiskDJ205GA20_____________________________A3VS____\5&1003ca0&0&0.0.0

Or Sometimes stored like this:

  IDE\DiskSJ305GA23_____________________________PG33S\6&2003Sa0&0&0.0.0

I want to get the 'A3VS' or 'PG33S' string. It's my firmware and is varied in length and type. I used to use:

            string[] split = PNP.Split('\\'); //where PHP is my string name
            var start = split[1].LastIndexOf('_');
            string mystring = split[1].Substring(start + 1);

But that only works for strings that don't end with __ after the firmware string. I noticed that some have an additional random ' _ ' after it.

Is RegEx the way to solve this? Or is there another way better

没有RegEx,就可以这样表示:

var firmware = PNP.Split(new[] {'_'}, StringSplitOptions.RemoveEmptyEntries)[1].Split('\\')[0];
string s = split[1].TrimEnd('_');    
string mystring = s.Substring(s.LastIndexOf('_') + 1);

If you want the RegEX way to do it here it is:

Regex regex = new Regex(@"\\.*_+(?<firmware>[A-Za-z0-9]+)_*\\");
var m1 = regex.Match("IDE\DiskSJ305GA23_____________________________PG33S\6&2003Sa0&0&0.0.0");
var g1 = m1.Groups["firmware"].Value;
//g1 == "PG33S"

Keep in mind you have to use [A-Za-z0-9] instead of \\w in the capture subexpression since \\w also matches an underscore (_).

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