简体   繁体   中英

How to use C# regex to find nth occurrence when also need to record nth record

Sorry for the confusing title,let me show an example: Let's I want to find the occurrence of 'hello' in a string which is

'xxxhellox|xxx|xxhelloxxx|···'

'|' is like a delimiter which means nth record,so I need to create a .Net project that produce the following output:

1,3···

So what is the best way to do that?

You could use Split with Linq,instead of Regex as following

var result = string.Join(",", str.Split('|')
                .Select((x,index)
                    =>new 
                     {
                       Value=x,
                       Index=index, // use index+1 if you need 1-based index
                       Contains=x.Contains("hello")
                      })
                .Where(x=>x.Contains)
                .Select(x=>x.Index));

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