如何使用.Net的RegEx从字符串中提取所有{}标记?

时间:2009-01-29 15:30:07

标签: .net regex extract token

我需要从给定字符串中提取用大括号标记的标记。

我尝试使用Expresso来构造可以解析的东西......

-------------------------------------------------------------
"{Token1}asdasasd{Token2}asd asdacscadase dfb db {Token3}"
-------------------------------------------------------------

并生成“Token1”,“Token2”,“Token3”

我尝试过使用..

-------------------------------------------------------------
({.+})
-------------------------------------------------------------

......但这似乎与整个表达相匹配。

有什么想法吗?

4 个答案:

答案 0 :(得分:6)

尝试

\{(.*?)\}
The \{ will escape the "{" (which has meaning in a RegEx).
The \} likewise escapes the closing } backet.
The .*? will take minimal data, instead of just .* 
which is "greedy" and takes everything it can.
If you have assurance that your tokens will (or need to) 
be of a specific format, you can replace .* with an appropriate 
character class. For example, in the likely case you 
want only words, you can use (\w*) in place of the (.*?) 
This has the advantage that closing } characters are not 
part of the class being matched in the inner expression, 
so you don't need the ? modifier). 

答案 1 :(得分:2)

尝试:

\{([^}]*)\}

这会将搜索范围内的搜索限制在关闭支撑上停止。

答案 2 :(得分:2)

另一种解决方案:

(?<=\{)([^\}]+)(?=\})

这使用前瞻和后视,因此根本不会消耗括号。

答案 3 :(得分:1)

大括号在正则表达式中具有特殊含义,因此您必须将它们转义。使用\{\}匹配它们。

相关问题