fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text.RegularExpressions;
  6.  
  7. public class Test
  8. {
  9. public static void Main()
  10. {
  11. var idx = 2; // Might be user-defined
  12. var subtext = "zero|one|two|three|four";
  13.  
  14. // Non-regex way - preferred
  15. var result = subtext.Split('|').ElementAtOrDefault(idx);
  16. Console.WriteLine(result);
  17.  
  18. // A regex way - only if no access to code
  19. var pat = $@"^(?:[^|]*\|){{{idx}}}([^|]*)";
  20. var m = Regex.Match(subtext, pat);
  21. if (m.Success) {
  22. Console.WriteLine(m.Groups[1].Value);
  23. }
  24. }
  25. }
Success #stdin #stdout 0.04s 134720KB
stdin
Standard input is empty
stdout
two
two