Reputation: 352
I have a telephone number that a person types into our program. We do not validate numbers on the user side (don't ask...). So what I did was used RegEx to strip all foreign characters and run a comparison with another RegEx (this is what the boss wants).
Once I have created a plain string for this number, I manually put hyphens into the string so our database can use it for comparison.
Unfortunately, when the user places a letter in the string, the string is shortened by one character, making my Substring throw an error. How would you rewrite this code (I'm thinking "if" statement but being that I'm fairly new to this and I don't want to inflate the code, I don't really trust myself at this point.)
telephone = Regex.Replace(telephone, "[^0-9.]", "");
StringBuilder sb = new System.Text.StringBuilder();
sb.Append(telephone.Substring(0, 3)
+ "-" + telephone.Substring(3, 3)
+ "-" + telephone.Substring(6, 4));
return sb.ToString();
I have checked this link and it wasn't what I was looking for.
UPDATE:
Expected result - Will still run with less than 10 numbers (including less than 4 or 3 numbers). Our table will still be populated with those options. We have other filtering on the panel, so the panel won't be big based off of 3-digit number
The user will just get a larger list (this is based off of company protocol). When I run it currently, the program just hangs with no updates to our panel. I have to physically restart the debugger from VS because there's no way to get out of our program.
Answer:
It was a mix of answers. I checked the one that I used for the actual telephone number itself:
telephone = Regex.Replace(telephone, "[^0-9.]", "");
if (telephone.Length > 3)
telephone = telephone.Insert(3, "-");
if (telephone.Length > 7)
telephone = telephone.Insert(7, "-");
return telephone;
Then I had to adjust the stored procedure to work correctly:
WHERE OfficePhone LIKE '%" + @newPhone + "%' ";
Thank you all for the help!
Upvotes: 2
Views: 3305
Reputation: 45967
i would avoid StringBuilder here. This approach won't throw a ArgumentOutOfRangeException and it will insert a -
in case of your number has the necessary length.
telephone = Regex.Replace(telephone, "[^0-9.]", "");
if (telephone.Length > 3)
telephone = telephone.Insert(3, "-");
if (telephone.Length > 7)
telephone = telephone.Insert(7, "-");
return telephone;
Upvotes: 3
Reputation: 151674
You didn't tell what the code should do if the cleaned up string doesn't match the expected length.
It seems like you expect a cleaned number to be 10 characters long (6 + 4). Then you can fix it for example by throwing an exception:
telephone = Regex.Replace(telephone, "[^0-9.]", "");
if (telephone.Length != 10)
{
throw new ArgumentException("Phone number length incorrect");
}
And there's not really any use for a stringbuilder here.
Upvotes: 4