user1742537
user1742537

Reputation: 19

Extracting ONLY number values between specific characters while ignoring string-number combination

I have for example this string,

|SomeText1|123|0#$0#62|SomeText2|456|6#83|SomeText3#61|SomeText1#41|SomeText5#62|SomeText3#82|SomeText9#40|SomeText2#$1#166|SomeText2|999|7#146|SomeText2#167|SomeText2#166|

I want to extract only number values and add them to list and later sum them. That means values,

|123|,|456|, |999|.

All other values like,

|SomeText1|,|SomeText2|,|SomeText2#$1#166|

shouldn't be in list.

I'm working with C#. I tried something like,

int sum = 0;

List<int> results = new List<int>();

Regex regexObj = new Regex(@"\|(.*?)\|");
Match matchResults = regexObj.Match(s);
while (matchResults.Success)
{
    results.Add(Convert.ToInt32(matchResults));
    matchResults = matchResults.NextMatch();
}

for (int i = 0; i < results.Count; i++)
{
    int bonusValues = results[i];
    sum = sum + bonusValues;
}

So basic idea is to extract values between | | characters and ignore one that are not pure digits like

|#16543TextBL#aBLa564B|

Upvotes: 0

Views: 230

Answers (4)

blaster
blaster

Reputation: 885

if you don't need specific the regex stuff you could easily split the string with:

string[] splits = s.split('|'); 

then you could loop through this set of strings and try to parse it to an integer. I

for(int i=0; i<splits.size(); i++){
  int num;
  bool isNum = int.TryParse(splits[i], out num);
  if(isNum){
   list.add(num);
  }
}

Upvotes: -2

Sayse
Sayse

Reputation: 43300

If regex isn't a definite requirement, you could use linq

stringName.Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
          .Where(x => x.All(char.IsNumber)).ToList(); 

With sum

stringName.Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
          .Where(x => x.All(char.IsNumber)).Sum(x => int.Parse(x)); 

Upvotes: 1

Dhaval Patel
Dhaval Patel

Reputation: 7601

you have to tried below menioned code

Regex regexObj = new Regex(@"\d+");

\d represents any digit, + for one or more. If you want to catch negative numbers as well you can use -?\d+.

Regex regexObj = new Regex(@"-?\d+");

Note that as a string, it should be represented in C# as "\d+", or @"\d+"

Upvotes: 0

L.B
L.B

Reputation: 116118

string input = @"|SomeText1|123|0#$0#62|SomeText2|456|6#83|SomeText3#61|SomeText1#41|SomeText5#62|SomeText3#82|SomeText9#40|SomeText2#$1#166|SomeText2|999|7#146|SomeText2#167|SomeText2#166|";

var numbers = Regex.Matches(input, @"\|(\d+)\|")
                   .Cast<Match>()
                   .Select(m => m.Groups[1].Value).ToList();

var sum = numbers.Sum(n => int.Parse(n));

Upvotes: 2

Related Questions