0

I'd like to check start with "Text" and next is numeric. I want this with Regex but can't make it well.

below is example and I only want to get "Test2018.txt", "Test2019.txt"

List<string> fileNames = new List<string>() {"Test2018.txt", "Test2019.txt", "TestEvent2018.txt", "TestEvent2019.txt"};
fileNames.Where(p => Regex.IsMatch(p, "Test^[0-9]+*") == true);
sugy21
  • 119
  • 9
  • 1
    `^` matches the start of the string. Check whether the start of the string is before or after `Test` and move the `^` accordingly – Ry- Jul 27 '18 at 00:23

2 Answers2

2

You could use this Regex:

^Test[0-9]+\.txt$

Where

  1. ^ denotes the start of the line.
  2. Test matches the literal text.
  3. [0-9] matches any numeric digit 0-9.
  4. + means at least once.
  5. \. matches the period.
  6. txt matches the literal text.
  7. $ denotes the end of the line.

And in C#:

var matchingFiles = fileNames.Where(p => Regex.IsMatch(p, @"^Test[0-9]+\.txt$"));
DavidG
  • 113,891
  • 12
  • 217
  • 223
  • 1
    `\d` matches all Unicode digits in .NET regular expressions, not just 0–9. `{1,}` is equivalent to `+`. You can use a verbatim string literal `@"…"` to avoid doubled backslashes. `$` optionally matches a newline before the end of the string; use `\z` to match only the end of the string. – Ry- Jul 27 '18 at 00:32
  • @Ry- Yeah, good call on the `\d` in particular, seems it's [faster like this](https://stackoverflow.com/questions/16621738/d-is-less-efficient-than-0-9) too. – DavidG Jul 27 '18 at 00:43
1

^ matches the start of the string, so it doesn’t make sense for it to go in the middle of your pattern. I think you also meant .* by *, but there’s no need to check the rest of the string when checking for IsMatch without an ending anchor. (That means [0-9]+ can also become [0-9].)

No need to use == true on booleans, either.

fileNames.Where(p => Regex.IsMatch(p, "^Test[0-9]"))
Ry-
  • 218,210
  • 55
  • 464
  • 476