我想知道这是否有可能在一次手术而不是两次?
1.
我用这个表达式来找一个没有空格的支撑:
(?<!\s)\)我用)代替它
2.
然后,我可以对开头的支撑做类似的操作:
\((?!\s)这个我用(代替
我是否可以使用OR做一个单一的查找表达式:
((?<!\s)\)|\((?!\s))用一个替换表达式可以同时做1和2吗?
发布于 2020-07-23 17:19:49
您可以使用“旁观者”,既可以向后看,也可以向前看,只需用空格替换即可。
Regex.Replace(text, @"(?<!\s)(?=\))|(?<=\()(?!\s)", " ")详细信息
(?<!\s)(?=\)) -一个没有紧跟空格的位置,并且紧跟在)后面。| -或(?<=\()(?!\s) -一个紧跟在(字符前面的位置,而不是紧跟在空格后面的。见C#演示
var input = @"(foobar) (fo) (ob (ar";
Console.WriteLine( Regex.Replace(input, @"(?<!\s)(?=\))|(?<=\()(?!\s)", " ") );
# => ( foobar ) ( fo ) ( ob ( ar发布于 2020-07-23 17:17:59
您可以使用(?<!\s)(\))|(\()(?!\s)和$2 $1替换。
详细信息
(?<!\s)(\)):匹配大括号),它前面没有空格作为第一组($1)
|:或
(\()(?!\s):匹配支撑(,后面没有空格作为第二组($2)
替换为$2 $1:一个匹配组将为空,因此它可以创建结果并在适当的位置添加空间
.NET代码示例:
public class Program
{
public static void Main()
{
// This is the input string we are replacing parts from.
string input = "(foobar) (fo) (ob (ar";
// Use Regex.Replace to replace the pattern in the input.
string output = Regex.Replace(input, @"(?<!\s)(\))|(\()(?!\s)", "$2 $1");
// Write the output.
Console.WriteLine(input);
Console.WriteLine(output);
}
}产出:
(foobar) (fo) (ob (ar
( foobar ) ( fo ) ( ob ( arhttps://stackoverflow.com/questions/63059503
复制相似问题