-3

I have this method that takes a string and only gets the numbers from it and trims the white spaces but it is not working:

 public static string ToNumericOnlyFAX(this string input)
   {
    if (input == "OFF6239750")
     {
      input = Regex.Replace(input, "[^0-9']", " "); - becomes "   6239750"
      input.TrimStart().Trim().TrimEnd(); - after any of these its still the above, I want it to be "6239750" 

        if (input.Length <= 10 && input == "6239750") - if the above works  then I can padleft
         {
         input.PadLeft(10, '0');
           }
         }
         return input; 
        }

how to I trim the string if the white spaces are in between the numbers such ass 603 123 4321???

CodeMan
  • 133
  • 3
  • 19
  • 3
    Strings are immutable - the `Trim()` calls etc return a new string - so you would use something like `input = input.Trim();`, and `input = input.PadLeft(10, '0');` etc – stuartd Jan 04 '17 at 22:11
  • And you could simply change your Regex to ... `Regex.Replace(input, "[^0-9']", "");` ... i mean you don´t need to replace with a whitespace. – Martin E Jan 04 '17 at 22:13
  • @stuartd how do I trim the spaces in between a string?? – CodeMan Jan 04 '17 at 22:26
  • 1
    HOW THE F*** IS THIS QUESTION DUPLICATE THERE IS A HUGE DIFFERENCE BETWEEN TRIMMING WHITE SPACE AND REPLACEING TWO WORDS IN A STRING. BEFORE YOU GUYS TAKE STUPID DECISIONS PLEASE READ THE QUESTION. – CodeMan Jan 04 '17 at 22:56
  • Indeed there is a difference between trimming whitespace and replacing two words. But neither of those are the problem you are having, the problem both you and the person in the duplicate are having is that you didn't know strings are immutable. Now you do. – Dour High Arch Jan 05 '17 at 00:06

2 Answers2

1

Additionally, why do you need to replace with spaces? For instance, you could change it to:

input = Regex.Replace(input, "[^0-9']", ""); - becomes "6239750".

Please note: This regular expression will remove all characters, including spaces.

0

Try to use:

string subjectString = "OFF6239750";
string resultString = null;
try {
    resultString = Regex.Match(subjectString, @"\d+").Value;
} catch (ArgumentException ex) {
    // Syntax error in the regular expression
}
Andie2302
  • 4,825
  • 4
  • 24
  • 43