C# 替换c中特定字符之间的空白
我正在寻找一个regexp或任何其他解决方案,可以让我替换特定非空白字符之间的所有空白字符。例如:C# 替换c中特定字符之间的空白,c#,regex,C#,Regex,我正在寻找一个regexp或任何其他解决方案,可以让我替换特定非空白字符之间的所有空白字符。例如: instance. method instance .method "instance" .method instance. "method" 可能吗 编辑: 换句话说,如果空格介于字母和点、点和字母、引号和点或点和引号之间,我想去掉空格。你在谷歌上搜索的是字符向前看和向后看。。。基本上,您要做的是使用正则表达式查找所有空格字符的实例,或者将字符串按空格分割。我更喜欢这一个,然后查看每个匹配的前
instance. method
instance .method
"instance" .method
instance. "method"
可能吗
编辑:
换句话说,如果空格介于字母和点、点和字母、引号和点或点和引号之间,我想去掉空格。你在谷歌上搜索的是字符向前看和向后看。。。基本上,您要做的是使用正则表达式查找所有空格字符的实例,或者将字符串按空格分割。我更喜欢这一个,然后查看每个匹配的前后位置,看看这些位置上的字符是否符合您的条件。然后,如有必要,在该位置进行更换
不幸的是,我不知道有哪种语句可以解决您试图执行的操作。您可以使用单词边界解析字符串:
^([\w\".]*)([\s])([\w\".]*)$
1美元可以给你第一部分。
2美元可以给你一个空白。
3美元就够了。这就是你想要的吗
使用lookaheads和lookbehinds:
var regex = new Regex("(?<=[a-zA-Z])\\s+(?=\\.)|(?<=\\.)\\s+(?=[a-zA-Z])|(?<=\")\\s+(?=\\.)|(?<=\\.)\\s+(?=\")");
Console.WriteLine(regex.Replace("instance. method", ""));
Console.WriteLine(regex.Replace("instance .method", ""));
Console.WriteLine(regex.Replace("\"instance\" .method", ""));
Console.WriteLine(regex.Replace("instance. \"method\"", ""));
正则表达式有四个部分:
(?<=[a-zA-Z])\s+(?=\.) //Matches [a-zA-Z] before and . after:
(?<=\.)\s+(?=[a-zA-Z]) //Matches . before and [a-zA-Z] after
(?<=")\s+(?=\.) //Matches " before and . after
(?<=\.)\s+(?=") //Matches . before and " after
我想扔掉空格,如果它在字母和点之间,点和字母之间,引号和点之间,或者点和引号之间
我会用这样的方式:
@"(?i)(?:(?<=\.) (?=[""a-z])|(?<=[""a-z]) (?=\.))"
或细分:
(?i) // makes the regex case insensitive.
(?:
(?<=\.) // ensure there's a dot before the match
[ ] // space (enclose in [] if you use the expanded mode, otherwise, you don't need []
(?=[a-z""]) // ensure there's a letter or quote after the match
| // OR
(?<=[a-z""]) // ensure there's a letter or quote before the match
[ ] // space
(?=\.) // ensure there's a dot after the match
)
在变量中:
var reg = new Regex(@"(?i)(?:(?<=\.) (?=[""a-z])|(?<=[""a-z]) (?=\.))");
另一种简单的解决方案是在点上拆分字符串,然后对其进行修剪。我认为使用regexp aloneOfcourse无法做到这一点,因为这是可能的-只要允许我指定那些特定的非空白字符和其他约束是什么。请让您的问题更具体一些,关于那些特定的非ws字符。任何解决方案都将不胜感激。目前我陷入困境,所以请随意提出任何建议:是否始终存在实例变量名?@elgonzo-我编辑了我的问题@T McKeown-不,这只是一个示例好吧,这是一个我无法自己编写的regexp:。谢谢@UlugbekUmirov你是如何创造这张美丽的图片的?这张图片展示了regex。与最初的问题完全无关,但是:你是怎么做到的?该死,胡安赢了我:-D
(?i) // makes the regex case insensitive.
(?:
(?<=\.) // ensure there's a dot before the match
[ ] // space (enclose in [] if you use the expanded mode, otherwise, you don't need []
(?=[a-z""]) // ensure there's a letter or quote after the match
| // OR
(?<=[a-z""]) // ensure there's a letter or quote before the match
[ ] // space
(?=\.) // ensure there's a dot after the match
)
var reg = new Regex(@"(?i)(?:(?<=\.) (?=[""a-z])|(?<=[""a-z]) (?=\.))");
Regex.Replace(instance, "([\\w\\d\".])\\s([\\w\\d\".])", "$1$2");