简体   繁体   中英

extract distinct list of number from a list of strings in C#

I have a list of strings with the following values:

"/manufacturers/244/rz-xvxcv/images/swed"
"/manufacturers/23/rz-gf/images/sltn"
"/manufacturers/34/rz-dffdf/images/five"
"/manufacturers/23/rz-gfgf/images/lead"
"/manufacturers/322/rz-dfg/images/carr"
"/manufacturers/3789/rz-fgdfgfg/images/zing"

I need to extract a distinct list of the number values that fall in the pattern /manufacturers/[int]/rz-

So in the above example my new list would contain: 244,23,34,322,3789

Can this be done using RegEx and Linq?

我只会使用Split而不是正则表达式

var numbers = paths.Select(p=>int.Parse(p.Split('/')[2])).ToList();

不是超级抽象或可重用,但很关键。

var numbers = paths.Select(p => int.Parse(p.Substring(15, p.IndexOf('/', 15) - 15)));

If you want to use RegEx and LINQ:

var regex = new Regex(@"(\d+)");
var numbers = paths.Select(i => regex.Match(i).Value).ToList();

you could use this patter
(\\d+)(?!.*\\1) not extracted in order though Demo

(               # Capturing Group (1)
  \d            # <digit 0-9>
  +             # (one or more)(greedy)
)               # End of Capturing Group (1)
(?!             # Negative Look-Ahead
  .             # Any character except line break
  *             # (zero or more)(greedy)
  \1            # Back reference to group (1)
)               # End of Negative Look-Ahead

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