Home > OS >  How to extract certain numbers that starts with tab/white spaces from a line in C#
How to extract certain numbers that starts with tab/white spaces from a line in C#

Time:12-15

I want to extract only the numbers starts with the tab

  \t2849\t\t” Here is the score”  

  \t123\t\t\” Here is the score”  

  \t12\t” Here is the score”  

  \t\1\t” Here is the score”  

  0  

  0  

I tried this

Foreach (string line in lines)  

If(regex.IsMatch(line, @”\s\d ”); 

List <string> score=new list<string>()

CodePudding user response:

How to extract certain numbers that starts with tab/white spaces

I think using a capturing group would be sensible here

var scores = new List<string>();
foreach (string line in lines)  
{
  var m = regex.Match(line, @"\s(?<s>\d )");
  if(m.Success) scores.Add(m.Groups["s"].Value);
} 

CodePudding user response:

If your input has actual TAB characters, this should do the trick:

\t(\d )

Then you need to get the second group, like match.Groups[1].Value (the first group is always the whole thing). Giving a group a name is overkill to me, just adds a bit of unnecessary complexity.

That will match 2849, 123 and 12, but not 1 or the last two 0.

If you really have \t in the input strings, just add a backslash: \\t(\d ).

  • Related