gpt4 book ai didi

c# - RegEx 匹配一个模式,只要它前面没有不同的模式

转载 作者:太空狗 更新时间:2023-10-29 20:59:57 24 4
gpt4 key购买 nike

我需要一个用于文本替换的正则表达式。示例:要匹配的文本是ABC(可以用方括号括起来),替换文本是DEF。这已经足够基本了。复杂的是,当 ABC 文本前面有模式 \[[\d ]+\]\.< 时,我不想匹配它 - 换句话说,当它前面是括号中的一个词或一组词,后跟一个句点。

下面是一些要匹配的源文本示例,以及进行正则表达式替换后的结果:

1. [xxx xxx].[ABC] > [xxx xxx].[ABC] (does not match - first part fits the pattern)
2. [xxx xxx].ABC > [xxx xxx].ABC (does not match - first part fits the pattern)
3. [xxx.ABC > [xxx.DEF (matches - first part has no closing bracket)
4. [ABC] > [DEF] (matches - no first part)
5. ABC > DEF (matches - no first part)
6. [xxx][ABC] > [xxx][DEF] (matches - no period in between)
7. [xxx]. [ABC] > [xxx] [DEF] (matches - space in between)

归根结底是:我如何指定前面的模式,当按照描述出现时将阻止匹配?在这种情况下,模式是什么? (正则表达式的 C# 风格)

最佳答案

你想要一个消极的后视表达。这些看起来像 (?<!pattern) ,所以:

(?<!\[[\d ]+\]\.)\[?ABC\]?

请注意,这不会强制在 ABC 周围匹配一对方括号;它只允许在前面有一个可选的左括号,在后面有一个可选的右括号。如果你想强制匹配或不匹配,你必须使用交替:

(?<!\[[\d ]+\]\.)(?:ABC|\[ABC\])

这使用非捕获括号来分隔交替。如果您想实际捕获 ABC,您可以将其变成一个捕获组。

ETA: 第一个表达式似乎失败的原因是它匹配 ABC] ,而 [ 前面没有禁止文本。左括号 [ 是可选的,所以它不匹配。解决这个问题的方法是将可选的开括号 [ 转移到否定的后视断言中,如下所示:

(?<!\[[\d ]+\]\.\[?)ABC\]?

它匹配和不匹配的示例:

[123].[ABC]: fail (expected: fail)
[123 456].[ABC]: fail (expected: fail)
[123.ABC: match (expected: match)
matched: ABC
ABC: match (expected: match)
matched: ABC
[ABC]: match (expected: match)
matched: ABC]
[ABC[: match (expected: fail)
matched: ABC

试图使左括号 ] 强制匹配右括号 ojit_code 的存在,如第二个模式预期的那样,比较棘手,但这似乎有效:

(?:(?<!\[[\d ]+\]\.\[)ABC\]|(?<!\[[\d ]+\]\.)(?<!\[)ABC(?!\]))

它匹配和不匹配的示例:

[123].[ABC]: fail (expected: fail)
[123 456].[ABC]: fail (expected: fail)
[123.ABC: match (expected: match)
matched: ABC
ABC: match (expected: match)
matched: ABC
[ABC]: match (expected: match)
matched: ABC]
[ABC[: fail (expected: fail)

示例是使用以下代码生成的:

// Compile and run with: mcs so_regex.cs && mono so_regex.exe
using System;
using System.Text.RegularExpressions;

public class SORegex {
public static void Main() {
string[] values = {"[123].[ABC]", "[123 456].[ABC]", "[123.ABC", "ABC", "[ABC]", "[ABC["};
string[] expected = {"fail", "fail", "match", "match", "match", "fail"};
string pattern = @"(?<!\[[\d ]+\]\.\[?)ABC\]?"; // Don't force [ to match ].
//string pattern = @"(?:(?<!\[[\d ]+\]\.\[)ABC\]|(?<!\[[\d ]+\]\.)(?<!\[)ABC(?!\]))"; // Force balanced brackets.
Console.WriteLine("pattern: {0}", pattern);
int i = 0;
foreach (string text in values) {
Match m = Regex.Match(text, pattern);
bool isMatch = m.Success;
Console.WriteLine("{0}: {1} (expected: {2})", text, isMatch? "match" : "fail", expected[i++]);
if (isMatch) Console.WriteLine("\tmatched: {0}", m.Value);
}
}
}

关于c# - RegEx 匹配一个模式,只要它前面没有不同的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4081294/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com