替换字符串的正则表达式,但方括号内的内容不受影响。

3

需要将所有正斜杠 (/) 替换为 >,但方括号中的除外。

输入字符串:

string str = "//div[1]/li/a[@href='https://www.facebook.com/']";

尝试的模式(无效):
string regex = @"\/(?=$|[^]]+\||\[[^]]+\]\/)";
var pattern = Regex.Replace(str, regex, ">");

预期结果:

">>div[1]>li>a[@href='https://www.facebook.com/']"
3个回答

1
你的想法是对的,使用回顾后缀是好的,但是改用否定前缀更好。
(?<!\[[^\]]*)(\/)

演示

更新你的 c# 代码后

string pattern = @"(?<!\[[^\]]*)(\/)";
string input = "//div[1]/li/a[@href='https://www.facebook.com/']";
var result = Regex.Replace(input, pattern, ">");

你将得到

>>div[1]>li>a[@href='https://www.facebook.com/']

0
如果你愿意使用 String.Replace,你可以这样做:
string input = "//div[1]/li/a[@href='https://www.facebook.com/']";
        string expected = ">>div[1]>li>a[@href='https://www.facebook.com/']";

        var groups = Regex.Match(input, @"^(.*)(\[.*\])$")
             .Groups
             .Cast<Group>()
             .Select(g => g.Value)
             .Skip(1);
        var left = groups.First().Replace('/', '>');
        var right = groups.Last();
        var actual = left + right;

        Assert.Equal(expected, actual);

这段代码的作用是将一个字符串分成两组,对于第一组,将其中的 / 替换为 >,就像你所描述的那样。第二组则保持不变。基本上,你不需要关心方括号内的内容。
Assert 是来自于 xUnit 单元测试。)

1
未能正常工作,输入为"//div[1]/a[1]/span[@class='_55pe'][1]"。 - Sandeep Dhamale
如果你期望的是 ">>div[1]>a[1]>span[@class='_55pe'][1]",那么它通过了我的测试。 - Aage

0
你可以从一个左方括号匹配到一个右方括号,或者在一个捕获组中捕获 /
在替换过程中,用 < 替换 /
Pattern
\[[^]]+\]|(/)
  • \[[^]]+\] 匹配从开头的 [ 到结尾的 ]
  • | 或者
  • (/) 捕获 / 到第一组中

正则表达式演示 | C#演示

例如

string str = "//div[1]/li/a[@href='https://www.facebook.com/']";
string regex = @"\[[^]]+\]|(/)";
str = Regex.Replace(str, regex, m => m.Groups[1].Success ? ">" : m.Value);
Console.WriteLine(str);

输出

>>div[1]>li>a[@href='https://www.facebook.com/']

这将删除括号内的所有内容,例如"//div[@class='_6a _3bcy'][1]"将被转换为"div>:nth-child(1)"。 - Sandeep Dhamale
@SandeepDhamale 我无法重现那个问题。请查看当前代码是否有效 https://rextester.com/YIVF99799 - The fourth bird

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接