简体   繁体   English

正则表达式(.NET)捕获除空间以外的所有内容

[英]Regex (.NET) Capture Everything But Spaces

I am attempting to use a regular expression with a single capture group to turn the following: 我试图将一个正则表达式与一个捕获组一起使用以进行以下操作:

[RuleID("MC304")]
[RuleID("MC 304")]
[RuleID("MC 30 4")]

into this: 到这个:

[RuleID("MC304")]
[RuleID("MC304")]
[RuleID("MC304")]

I have accomplished this result using this regex101 example but it is pretty rudimentary: 我已经使用此regex101示例完成了此结果,但是非常简单:

I matched 我配对了

\[RuleID\("(\w*)\s*(\w*)\s*(\w*)\s*"\)\]

and replaced with 并替换为

[RuleID("$1$2$3")]

I would like to be able to use non-capturing groups nested inside of a capture group so I can just replace the content inside of the double quotes with $1 instead of having to concatenate $1$2$3 but I don't believe this is possible. 我希望能够使用嵌套在捕获组内部的非捕获组,因此我可以将双引号内的内容替换为$1而不必将$1$2$3连接起来,但是我认为这是不可能的。

If anyone has any guidance on how to write a regular expression that is more reusable than having to duplicate (\\w*)\\s* for every space I expect I'd greatly appreciate the help! 如果有人对如何编写正则表达式有任何指导,而不是每个空间都必须重复(\\w*)\\s* ,那么我希望我能为您提供帮助!

Edit 编辑

I am wanting this solution to be generic for any alphanumeric string with spaces in between. 我希望此解决方案对于任何字母数字字符串之间具有空格都是通用的。 The example above is for "MC304" but it could just as well be any number letter combination with spaces. 上面的示例适用于“ MC304”,但也可以是带空格的任何数字字母组合。

Note: I am using Visual Studio's built in find and replace feature to remove spaces from all RuleID attributes across the entire solution. 注意:我正在使用Visual Studio的内置查找和替换功能来删除整个解决方案中所有RuleID属性中的空格。

After clarifications in the comments on the usage, you can use this pattern to match your strings. 在用法说明中澄清之后,您可以使用此模式来匹配您的字符串。 Note that you need to provide the length (without spaces) of your search string, and the search string itself (again without the spaces). 请注意,您需要提供搜索字符串的长度(不带空格),以及搜索字符串本身(同样不带空格)。

([mc304](?:\s+?)?){5}

This works by using a non capturing group to isolate spaces, and by using a character class to specify which characters are legal. 通过使用一个非捕获组来分隔空格,并通过使用一个字符类来指定哪些字符是合法的,这可以起作用。 Note that you should not be repeating letters or numbers in there, so if you are looking for "mc300", you would use [mc30] and a length of 5. Unfortunately this will also match mc030 and mc003 etc... But maybe you can work with that by making sure manually before pressing replace... 请注意,您不应在其中重复字母或数字,因此,如果您要查找“ mc300”,则可以使用[mc30],长度为5。不幸的是,这也将匹配mc030和mc003等。但是也许您可以通过在按替换之前手动确保...来进行操作...

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

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