C#正则表达式:匹配含等号且无逗号、嵌套括号的方括号内容
Hey there! Let's adjust your regex to meet that requirement—here's how to do it:
Solution
To modify your existing regex so it only matches square brackets containing at least one = (while still excluding commas and nested brackets), use this pattern:
\[([^,\[\]]*=[^,\[\]]*)\]
How It Works
Let's break down the parts to see what changed from your original regex:
\[and\]: Still match the opening and closing square brackets literally, just like before.([^,\[\]]*=[^,\[\]]*): This is the updated capturing group for the content inside the brackets:[^,\[\]]*?: Matches zero or more non-greedy characters that aren't commas, opening brackets, or closing brackets. This covers any text before the=.=: The mandatory equals sign—this ensures we only match brackets that have at least one=inside.[^,\[\]]*?: Matches zero or more non-greedy characters that aren't commas, opening brackets, or closing brackets. This covers any text after the=.
Edge Cases & Adjustments
If you want to disallow cases where the = is at the very start or end of the bracket content (like [=Test] or [Test=]), you can tweak the regex to require at least one character on both sides of the =:
\[([^,\[\]]+=[^,\[\]]+)\]
Test Cases
Let's verify this works with your examples and other scenarios:
- ✅ Matches:
[Test=Test]→ capturesTest=Test - ✅ Matches:
[Test=Test;Test2=Test2]→ capturesTest=Test;Test2=Test2 - ❌ Doesn't match:
[NoEquals](no=) - ❌ Doesn't match:
[Has,Comma=Test](contains comma) - ❌ Doesn't match:
[Nested[Brackets]=Test](nested brackets)
That should cover exactly what you need!
内容的提问来源于stack exchange,提问作者LordCaos
相关产品推荐
相关产品推荐

