2009-04-30 68 views
0

如何從字符串中僅提取格式化部分。例如: 如果我有一個字符串=「警告:發生錯誤{0},{1,9}模塊已完成{2:0%}。」 我想提取{0},{1,9}和{2:0%}到一個sting數組中。是否有一個正則表達式或其他可以完成的事情,除了我的交替使用Substring indexof'{'和'}'來循環字符串的方式?如何從字符串中提取格式化部分

回答

1

「\ {[^}] + \}」的某些變體不起作用嗎?通過從比賽開始到結束找到比賽和子串來運行它。

0
new Regex(@"\{[0-9:,% .]+\}"); 

您可能需要對其進行調整/調整,以考慮您在示例中未提供的任何其他格式選項。

0

在Java中,Matcher類採用正則表達式並將返回所有匹配的子字符串。

例如:

String str = "Warning: the error {0} has occurred. {1, 9} module has {2:0%} done."; 

Matcher matcher = pattern.matcher("{.*}"); 
while (matcher.find()){ 
    String matched = matcher.group() 
    \\do whatever you want with matched 
} 
1

下面的代碼是從它使用非貪婪匹配其它不同的答案( 「*?」):

private static void Main(string[] args) { 
     const string input = "Warning: the error {0} has occurred. {1, 9} module has {2:0%} done."; 
     const string pattern = "{.*?}"; // NOTE: "?" is required here (non-greedy matching). 
     var formattingParts = Regex.Matches(input, pattern).Cast<Match>().Where(item => item.Success).Select(item => item.Groups[0].Value); 
     foreach (var part in formattingParts) { 
      Console.WriteLine(part); 
     } 
    } 
+0

+1我開始用命名匹配寫一些東西來幫助單獨提取每個部分,但是上面的代碼阻止了我 - 非常好的解決方案 – 2009-05-01 15:47:43