How to remove the string "[xyz]" from a file name using Regex?

I have a file name 0154562A5BS16101[001]in which I would like to delete "[001]" just to leave 0154562A5BS16101.

I tried using regex:

var output = Regex.Replace(filename, @"[]", string.Empty);

But he throws:

System.ArgumentException: 'parsing '[]' - Unterminated [] set.'

It seems to me that this is quite easy for Regex masters, but I do not have much experience with Regex.

+4
source share
1 answer

Since [and ]are meta characters in the regular expression language, you need to avoid them. You also need to tell the regular expression that you want to match everything with a closing square bracket:

var output = Regex.Replace(filename, @"\[[^\]]*\]", string.Empty);

\[ \] , . [^\]]* , .

+4

Source: https://habr.com/ru/post/1674618/


All Articles