1

I am looking for a regular expression to match the fileNamePattern. Files are pdf can have these names: 8 alphanumeric chars, -, 4 alphanumeric chars, -, 4 alphanumeric chars, -, 4 alphanumeric chars, -, 12 alphanumeric chars + .pdf.

Examples:

5b7f991f-0726-4dd5-856e-7cea820f02c5.pdf
138bcee6-db7f-47a7-97bf-69c0b3989698.pdf
e988315b-ade7-48e5-9733-35bb59a3c28d.pdf

I am using

^[A-Z][0-9]{8}[-][A-Z][0-9]{4}[-][A-Z][0-9]{4}[-][A-Z][0-9]{4}[-][A-Z][0-9]{12}[.]pdf

However, I am not sure it is correct as I get no matches.

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
user2897967
  • 337
  • 2
  • 6
  • 23

3 Answers3

1

Regex r = new Regex(@"^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}\.pdf$");

If you explicitly don't want underscores, you can use:

^[a-zA-Z\d]{8}-[a-zA-Z\d]{4}-[a-zA-Z\d]{4}-[a-zA-Z\d]{4}-[a-zA-Z\d]{12}\.pdf$

Regex is case-sensitive (unless you specify it to ignore case using RegexOptions. Right now the main issue is that your regex is saying to match a letter then match n digits instead of matching n alphanumeric characters.

With setting the case insensitive flag, your regex can simplify to:

^[A-Z\d]{8}-[A-Z\d]{4}-[A-Z\d]{4}-[A-Z\d]{4}-[A-Z\d]{12}\.pdf$

Daichi Jameson
  • 310
  • 2
  • 10
0

This should work /(\w{8})-(\w{4})-(\w{4})-(\w{4})-(\w{12})(.pdf)/i

I tried it at here at RegEx Testing

\w = alphanmumeric {n} = times the sign should appear

gi = are flags: "i" = case insensitive.

S.H
  • 365
  • 3
  • 13
0

You only match uppercase letters in your regex, and when you use [A-Z][0-9]{4} you do not match four alphanumeric chars, you match a letter followed with 4 digits.

So, you need to merge [A-Z][0-9] into single character classes [A-Z0-9] and then use a case insensitive flag.

Also, you need to use $ at the end of the regex to make the pattern match the entire string.

Use

^[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}[.]pdf$

See the regex demo

In C#,

var rx = new Regex(@"^[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}[.]pdf$", RegexOptions.IgnoreCase);

Note that case insensitivity can be set with an inline modifier (?i):

var pattern = @"(?i)^[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}[.]pdf$";
// check if the string matches the pattern
if (Regex.IsMatch(s, pattern) 
{
    // The string matches...
}
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397