-1

I want to create a program that takes in a string and output just the numbers, hopefully using regex to save effort, here is the following code i have

public void main{
    string str = "abc-123.44def";
    string output = "";
    bool setA = false;

    StringBuilder stb = new StringBuilder();
    for(int i=0; i<str.Length; i++){
        switch(str[i]){
            case 'b':
                setA = foo();
                break;
            case 'c':
                foo2();
                break;
            case '\d':
            case '-':
            case '.':
                if(setA){
                    stb.Append(str[i]);
                }
                break;
            default:
                break;
        }
    }
    output = stb.toString();
}

public void foo(){
    return true;
}

Problem is, the editor gives me a error saying

Unrecognized Escape Sequence

on the '\d' part. Ive seen online sample codes where such usage is allowed so im not sure why my editor is not accepting this. Can someone explain to me what the problem is and how to solve it?

EDIT: It seems like my sample was alittle misleading. I cannot just take out the numbers from the strings by itself since other characters in the string calls different functions and the number characters i want to take out depends on some of them. I updated the code to correct the misinformation.

Shanan
  • 33
  • 4

2 Answers2

1

You can use the Char.IsDigit() to check if a char is a digit (as I mentioned in my first comment):

string str = "abc-123.44def";
string output = "";
bool setA = false;

StringBuilder stb = new StringBuilder();
for(int i=0; i<str.Length; i++){
    switch(str[i]){
        case 'b':
          setA = foo();
          break;
        case 'c':
          foo2();
          break;
    //  case '\d': REMOVE IT
        case '-':
        case '.':
          if(setA){
             stb.Append(str[i]);
          }   
          break;
        default:
          if (Char.IsDigit(str[i])) stb.Append(str[i]); // Add this
            break;
          }
    }
    output = stb.ToString();
}

Result:

enter image description here

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

Is this what you are looking for ?

    Regex r = new Regex(@"\d+");
    string s = "abc-123.44def";

    var matches = r.Matches(s);
    List<string> numbersOnly = new List<string>();

    foreach (Match match in matches)
        numbersOnly.Add(match.Value);

    foreach (var number in numbersOnly)
        Console.WriteLine(number);

//output: 
//123
//44
Veverke
  • 9,208
  • 4
  • 51
  • 95