You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

正则表达式需求:替换方括号外斜杠为>,现有模式失效

Fixing the Slash Replacement Regex (Excluding Bracketed Content)

Got it, let's get your regex working correctly! You want to replace all / characters with > except those inside square brackets ([]), and your current pattern isn't hitting the mark.

The Problem with Your Original Regex

Your regex @"\/(?=$|[^]]+\||\[[^]]+\]\/)" has a few logical inconsistencies:

  • The [^]]+\|| part includes an unescaped | that acts as an OR operator, but it doesn't serve any useful purpose here
  • It doesn't properly account for the full scope of square-bracketed blocks, so it fails to reliably exclude slashes inside [...]

The Correct Solution

We need a regex that matches a / only if it's not inside any square brackets. Here's a pattern that does exactly that, along with working code:

string str = @"//div[1]/li/a[@href='https://www.facebook.com/']";
// Regex to match slashes NOT inside square brackets
string regexPattern = @"\/(?=(?:[^[\]]*\[[^[\]]*\])*[^[\]]*$)";
var result = Regex.Replace(str, regexPattern, ">");

What This Regex Does

Let's break down the pattern to understand why it works:

  • \/: Matches the literal / we want to replace
  • (?=...): A positive lookahead that checks the content after the slash to ensure it meets our condition
    • (?:[^[\]]*\[[^[\]]*\])*: Matches any number of complete square-bracket blocks (e.g., [1], @href='https://www.facebook.com/') — this skips over all bracketed content
    • [^[\]]*$: Ensures that after any bracketed blocks, there are only non-bracket characters until the end of the string. This guarantees the slash we're matching isn't inside an unclosed bracket.

Expected Output

Running the code above will give you exactly the result you want:

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

内容的提问来源于stack exchange,提问作者Sandeep Dhamale

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:50:51