-1

I have a file naming pattern such as

this is a 9876 file name .1234.ext

OR

thisisa9876filename .4321.ext

I can return a match easily enough for .1234.ext by using

/(\.\d{4}\.ext)$/

What I want to do is find a match if it is not that format. e.g.

thisisa9876filename.123.ext

OR

this is a 9876 file name.txe

So effectively if it doesn't match that pattern I want to return a match.

I can't seem to work out any solution to this. Any help would be greatly appreciated.

Kent
  • 1

2 Answers2

0

To pick up on the solution suggested by @Nick, and assuming that you work with, or have access to, R, the solution could be this: If this is (like) your data:

data <- c("thisisa9876filename .4321.ext", "thisisa9876filename.123.ext", 
          "this is a 9876 file name.txe", "this is a 9876 file name .1234.ext")

then you can use grepand its invert = T argument to match anything the pattern does not match:

grep("\\d{4}\\.ext$", data, value = T, invert = T)
[1] "thisisa9876filename.123.ext"  "this is a 9876 file name.txe"
Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34
0

If a negative lookahead (?! is supported, you could assert that the string does not end with your pattern:

^(?!.*\.\d{4}\.ext$).+$
  • ^ Start of string
  • (?! Negative lookahead, assert what is on the right is not
    • .*\.\d{4}\.ext$ Match a dot and 4 digits followed by .ext at the end of the string
  • ) Close lookahead
  • .+ Match any char except a newline 1+ times
  • $ End of the string

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • Thats terrific the forth bird. Thank you. If you had the time to explain the logic that would be really helpful thank you. – Kent Dec 17 '19 at 01:07
  • @Kent I have added an explanation of the different parts of the pattern. – The fourth bird Dec 17 '19 at 10:41
  • awsome thank you. That makes sense now. It appears my problem was not matching all characters after the negative lookahead. So effectively it is saying match all characters if the negative lookahead is true. Thanks so much @the forth bird – Kent Dec 20 '19 at 01:49