C#正则表达式匹配大括号-仅内容? (不包括大括号) [英] C# Regex.Match curly brackets- contents only? (exclude braces)
本文介绍了C#正则表达式匹配大括号-仅内容? (不包括大括号)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直无法找到答案:我可以使用 Regex.Matches
方法仅返回商品的内容吗?
I've been unable to find an answer on this: can I use the Regex.Matches
method to return only the contents of items with curly braces?
如果我使用正则表达式({[^}] *})
我的 MatchCollection
值包括花括号。我想匹配,但是只返回内容。到目前为止,这是我所拥有的:
If I use the Regex ({[^}]*})
my MatchCollection
values includes the braces. I want to match, but then only return the contents. Here's what I have so far:
Regex regex = new Regex(({[^}]*}), RegexOptions.IgnoreCase);
MatchCollection matches = regex.Matches("Test {Token1} {Token 2}");
// Results include braces (undesirable)
var results = matches.Cast<Match>().Select(m => m.Value).Distinct().ToList();
推荐答案
我一直喜欢它明确。因此,您可以使用正向后看(?< = ...)和正向前瞻(?= ...)组:
I always liked it explicit. So you can use "positive lookbehind" (?<=...) and "positive lookahead" (?=...) groups:
(?<=\{)
[^}]*
(?=\})
这意味着:
- 在之前需要匹配
- 收集文本(当然)-正如我可能也是[^ {}] *之前所说的那样
- 需要用大括号比赛结束之后
- require opening curly bracket before match
- collect text (of, course) - as commented before I may be [^{}]* as well
- require closing curly bracket after match
这篇关于C#正则表达式匹配大括号-仅内容? (不包括大括号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文