Regular expression

PARTH DESAI 61 Reputation points
2021-04-21T20:20:32.273+00:00

What should be the regular expression for
<something>_<something else>.xml

I am trying below but It doesn't return any matched for valid pattern.

Regex.Matches(file.Name, @"^.[a-z0-9][_][a-z0-9].[Xx][Mm][Ll]$")

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
7,024 questions
{count} votes

Accepted answer
  1. Timon Yang-MSFT 9,501 Reputation points
    2021-04-22T09:17:22.623+00:00

    This way should work too:

    Regex.Matches(file.Name, "[a-z0-9]+_([a-z0-9]+[_-])*[a-z0-9]+[.]xml$", RegexOptions.IgnoreCase);  
    

    Since the suffix may be uppercase or lowercase, you need to use the Regex.Matches overload with RegexOptions as a parameter.


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    No comments

2 additional answers

Sort by: Most helpful
  1. Viorel 83,016 Reputation points
    2021-04-21T20:30:56.49+00:00

    Theoretically, “something” can be expressed with “.+”, but it seems that you only accept letters and digits, therefore try this expression:

    (?i)^[a-z0-9]+_[a-z0-9]+[.]xml$

    If you need something special, then explain the rules and show examples.

    (To insert the code try using the "101" button, because your expression is probably distorted).


  2. Viorel 83,016 Reputation points
    2021-04-22T08:44:31.947+00:00

    For your new details, try this expression:

    Regex.Matches(file.Name, @"(?i)^(?! )[^\x00-\x1F\\/.*?:<>""|]+_[a-z0-9-]+[.]xml$")
    

    You can adjust it to allow the valid '.' inside the names.

    No comments