Click here to Skip to main content
15,911,139 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more: , +
hello, i have a form with a textBox and a label, i want to check if the textBox Text is finishing by ".pdf" or ".jpg", then i want to show the extention in the label :

C#
public Form1()
        {
            InitializeComponent();

            textBox1.Text = "http://www.site.com/Documents/file.pdf";

            Match matchPdf = Regex.Match(textBox1.Text, @"\*+(.pdf|.PDF)$/",
                RegexOptions.IgnoreCase);
            Match matchImg = Regex.Match(textBox1.Text, @"\*+(.jpeg|.JPEG|.gif|.GIF| .png|.PNG)$/",
                RegexOptions.IgnoreCase);

            if (matchPdf.Success)
            {
                label1.Text = "PDF";
            }
            else if (matchImg.Success)
            {
                label1.Text = "IMG";
            }
            else label1.Text = "UNIVERSAL";
        }



The label is always showing "Universal"... someone can help me please!
Posted
Updated 8-May-13 4:13am
v2

1 solution

I can see at least one bug: at the very beginning, use '.+', not '\*+'. Just think about it: you are not looking for a wildcard, but for some file characters, and '*' cannot ever appear in a file name.

[EDIT]

Besides, you probably would need one more file naming scheme: .JPG. One more problem: you are not taking into account the names like *.GiF, *.GIf, *.Gif etc., as some user may legitimately use them. That said, you should not try to list all the cases, but rather need to use a case-insensitive Regex.

[END EDIT]

This Regex would not be comprehensive though: you should also check up for correct URI scheme, exclude the characters not allowed in paths, etc. Are you sure you the you want to validate it at all? Perhaps you could use one of the file dialogs? (I don't know, because I don't know your application.)

—SA
 
Share this answer
 
v2
Comments
Nnorss 8-May-13 10:08am    
thanks for your attention, it is the first time that i use regex, i really need to validate the extention to tell the program what to do if its, pdf, what to do if it's jpeg.....
Sergey Alexandrovich Kryukov 8-May-13 10:17am    
Is your problem solved?
—SA
Nnorss 8-May-13 10:20am    
No! i'm still searching for the solution :s
Sergey Alexandrovich Kryukov 8-May-13 10:32am    
What are the problems?
—SA
Nnorss 8-May-13 10:36am    
problem resolved :D

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900