简体   繁体   English

如何合并2个简单的RegEx?

[英]How to merge 2 simple RegEx's?

I have the following C# code to replace . 我有以下C#代码替换. 's and + 's with spaces: 的和+的使用空格:

string MyString = "this.is.just+an++example--here!are$more characters";
MessageBox.Show(Regex.Replace(MyString, @"[\.\+]", " "));

Sometimes this might result in excess whitespace (as in, between an and example ). 有时,这可能会导致过量的空白(如,间anexample )。

How can I also add the following RegEx to my existing RegEx, so there is only a single RegEx call? 如何将以下RegEx也添加到现有RegEx中,因此只有一个RegEx调用?

Regex.Replace(MyString, @"[ ]{2,}", " ");

This will remove excess whitespace. 这将删除多余的空格。 All other characters should remain untouched. 所有其他字符应保持不变。

Any alternate solutions are also welcome! 也欢迎任何其他解决方案!

Maybe you should match multiple characters in the first place. 也许您应该首先匹配多个字符。 Change the regexp to "[\\.\\+]+" to match one or more . 将正则表达式更改为"[\\.\\+]+"以匹配一个或多个. or + signs. +号。 For example, "a...++b" would result in "ab" 例如, "a...++b"将导致"ab"

MessageBox.Show(Regex.Replace(MyString, @"[\.\+]+", " "));

You should try this. 您应该尝试一下。 You don't need to escape the . 您无需逃脱. if it is inside a character class 如果它在角色类中

[.\+]+|[ ]{2,}

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

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