I figured I would write this little tutorial about C# and Regex since it is still fresh in my mind.
The code below shows how to remove all spaces from a string:
Code:using System; using System.Collections.Generic; using System.Text; namespace regexconsole { class Program { static void Main(string[] args) { // Create a string and display it to the console string display = "I have several spaces in me"; Console.WriteLine(display); // Replaces all spaces with 1 space display = System.Text.RegularExpressions.Regex.Replace(display," +", " "); Console.WriteLine(display); // Make it pause Console.ReadLine(); } } }
Here is how to determine if a string is a number or not
Code:using System; using System.Collections.Generic; using System.Text; namespace regexconsole { class Program { static void Main(string[] args) { // Create an integer and display it string number = "64"; Console.WriteLine(number); // Determine if it is a positive number if (System.Text.RegularExpressions.Regex.IsMatch(number, ("[0-9]*"))) { Console.WriteLine("This is a number"); } else { Console.WriteLine("This is not a number!"); } // Make it pause Console.ReadLine(); } } }
That is it for now. I will post more later.
thanks alot man, really nice.
It would be nice if you could tell something about regular expressions, and how they works, for those people there doesn't know what it actually is.
I wouldn't call this a tutorial, it had been better with, "Examples" or something.
i'm rewrite follow your tut, but it show incorrect.
are you sure write correct this code?
sr i'm not not fluent English. I'm from Vietnam
The author of this tutorial hasn't been active anymore since 2008.
What's wrong with it? The screenshot tells me that it's working correct. I mean 55 IS a number...
yeah the second code piece has a bug in it...it always show "This is a number" or a kinda that even when you enter a piece of text
Oh didn't see the right part of your screenshot when i posted that...
Yes in the second part of his code you must replace
by user input or something.Code:string number = "64";
The regex seems correct
[0-9] -- means: a character between and including 0 and 9
* -- means: 0,1 or more times
So if the string you give has only characters between 0 and 9, it'll validate.
for letters there is a difference in case and you can't do [a-Z] because it'll validate a bunch of extra stuff too. It uses the ascii table and you'll see that the range a-Z will be wrong: Ascii Table - ASCII character codes and html, octal, hex and decimal chart conversion
i'm tried "string number = "64";" as author's code, but it always show "This is a number"
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks