【问题标题】:Replace X or Y with J or Q using expressions使用表达式将 X 或 Y 替换为 J 或 Q
【发布时间】:2020-07-23 17:01:55
【问题描述】:

我想知道这是否可以在一次操作而不是两次操作中实现?

1.

我有这个表达式来查找前面没有空格的大括号:

(?<!\s)\)

我将其替换为 )

2.

然后我可以为左大括号做类似的事情:

\((?!\s)

我用( 替换这个

我能否以某种方式使用 OR 执行单个查找表达式:

((?<!\s)\)|\((?!\s))

并且用一个替换表达式以某种方式同时执行 1 和 2?

【问题讨论】:

  • @Thefourthbird ...不完全-我找到括号并将其替换为空格和相同的括号。
  • 我明白了,问题中没有显示空格。我赞成这个问题。我会删除评论。

标签: .net regex


【解决方案1】:

您可以使用 (?&lt;!\s)(\))|(\()(?!\s)$2 $1 替换。

Regex Demo

详情

(?&lt;!\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 ( ar

【讨论】:

  • 已更新。谢谢你的解释。
【解决方案2】:

您可以使用lookarounds,包括lookbehind 和lookahead,只需用空格替换

Regex.Replace(text, @"(?<!\s)(?=\))|(?<=\()(?!\s)", " ")

regex demo

详情

  • (?&lt;!\s)(?=\)) - 前面没有空格,后面紧跟 ) 的位置
  • | - 或
  • (?&lt;=\()(?!\s) - 前面紧跟 ( 字符且后面不紧跟空格的位置。

C# demo

var input = @"(foobar)  (fo) (ob (ar";
Console.WriteLine( Regex.Replace(input, @"(?<!\s)(?=\))|(?<=\()(?!\s)", " ") );
# => ( foobar )  ( fo ) ( ob ( ar

【讨论】:

  • 已更新。非常好的维克托。
猜你喜欢
  • 2018-01-06
  • 2011-12-01
  • 1970-01-01
  • 2021-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-15
  • 1970-01-01
相关资源
最近更新 更多