QkiZ
QkiZ

Reputation: 880

Match all except specific group

I have a test string repo-2019-12-31-14-30-11.gz and I want to exclude 2019-12-31-14-30-11.gz from that string and match everything else. Digits with date and hour can be different. String at the beginning of text can be any word, can contain digits, dashes or underscores. Constant characters are:

I tried following regex:

^.*(?!-\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}.gz$)

but it always matches whole text

Upvotes: 1

Views: 929

Answers (1)

The fourth bird
The fourth bird

Reputation: 163287

The pattern that you tried ^.*(?!-\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}.gz$) always matches the whole text because .* will first match until the end of the string. Then at the end of the string, it will assert that what is directly on the right is not the date like pattern.

That assertion will succeed as it is at the end of the string.


You could use a capturing group with a character class matching word characters or a hyphen and use that in the replacement:

^([\w-]+)-\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}\.gz$

Regex demo

If the beginning can not start with an underscore and can not contain consecutive underscores, you could repeat matching a hyphen and a word character in a grouping stucture \w+(?:-\w+)*

^(\w+(?:-\w+)*)-\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}\.gz$

Regex demo

Upvotes: 1

Related Questions