如何从字符串中提取格式化部分
问题描述:
如何从字符串中仅提取格式化部分。例如: 如果我有一个字符串=“警告:发生错误{0},{1,9}模块已完成{2:0%}。” 我想提取{0},{1,9}和{2:0%}到一个sting数组中。是否有一个正则表达式或其他可以完成的事情,除了我的交替使用Substring indexof'{'和'}'来循环字符串的方式?如何从字符串中提取格式化部分
答
“\ {[^}] + \}”的某些变体不起作用吗?通过从比赛开始到结束找到比赛和子串来运行它。
答
new Regex(@"\{[0-9:,% .]+\}");
您可能需要对其进行调整/调整,以考虑您在示例中未提供的任何其他格式选项。
答
在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
}
答
下面的代码是从它使用非贪婪匹配其它不同的答案( “*?”):
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);
}
}
+1我开始用命名匹配写一些东西来帮助单独提取每个部分,但是上面的代码阻止了我 - 非常好的解决方案 – 2009-05-01 15:47:43