简体   繁体   English

如何使用Regex从文件名中删除字符串“[xyz]”?

[英]How to remove string “[xyz]” from filename with Regex?

I have the filename 0154562A5BS16101[001] in which I would like to remove the "[001]" to just leave 0154562A5BS16101 . 我有文件名0154562A5BS16101[001] ,其中我想删除“[001]”,只留下0154562A5BS16101

I have tried using the regex: 我试过使用正则表达式:

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

But it throws: 但它抛出:

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

I feel like this is a pretty easy for Regex masters, but I don't have much experience with Regex. 我觉得这对于Regex大师来说非常容易,但我对Regex没有多少经验。

Since [ and ] are metacharacters in regex language, you need to escape them. 由于[]是正则表达式语言中的元字符 ,因此您需要转义它们。 You also need to tell regex that you want to match everything up to the closing square bracket: 您还需要告诉正则表达式,您希望将所有内容匹配到结束方括号:

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

\\[ and \\] at the ends are square brackets that you want to replace. \\[\\]在末尾是要替换的方括号。 The [^\\]]* section in the middle matches any number of characters other than the closing square bracket. 中间的[^\\]]*部分匹配结束方括号以外的任意数量的字符。

Demo. 演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM