Click here to Skip to main content
15,923,006 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
File name is text1eb4617fd-4876-4c52-aa5b-21f8be8fb0f8.txt
it should return true because it contains GUID

If File name is text1eb4617fd-4876-f8.txt or text1.txt
it should return false as it does not contain any GUID
Posted

A regular expression would be perfect for that:

C#
using System.Text;

string pattern = @"^text(?<guid>[0-9a-zA-Z]{8}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{12})\.txt$";

Regex regex = new Regex(pattern, RegexOptions.Compile | RegexOptions.CultureInvariant);

string input1 = "text1eb4617fd-4876-4c52-aa5b-21f8be8fb0f8.txt";
string input2 = "texteb4617fd-4876-4c52-aa5b-21f8be8fb0f8.txt";

bool input1Matches = regex.IsMatch(input1); // input1Matches will be false
bool input2Matches = regex.IsMatch(input2); // input2Matches will be true

As a bonus, if you want to get the Guid, it is a simple as:
C#
Match m = regex.Match(input2);
Guid guid = Guid.Parse(m.Groups["Guid"].Value);

Note: the Guid you are presenting is not a valid one: its first block should hold exactly 4 bytes, buty the example you give would need 5 bytes to store 1eb4617fd. That's why I used two string variables in my example.

Hope this helps.
 
Share this answer
 
v3
Try This one
C#
protected void Page_Load(object sender, EventArgs e)
   {

       bool a = IsHavingGUID("text1eb4617fd-4876-4c52-aa5b-21f8be8fb0f8.txt");
       bool b = IsHavingGUID("text1.txt");
   }

   public bool IsHavingGUID(string input)
   {
       MatchCollection guids = Regex.Matches(input, @"(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}");
      return guids.Count>0;
   }
 
Share this answer
 

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