更新
这是我想出来的。我还没有测试它,因为它是更大代码的一部分,仍然需要移植。
你能看到任何不合适的东西吗?
private const string tempUserBlock = "%%%COMPRESS~USER{0}~{1}%%%";
string html = "some html";
int p = 0;
var userBlock = new ArrayList();
MatchCollection matcher = preservePatterns[p].Matches(html);
int index = 0;
StringBuilder sb = new StringBuilder();
int lastValue = 0;
foreach(Match match in matcher){
string matchValue = match.Groups[0].Value;
if(matchValue.Trim().Length > 0) {
userBlock.Add(matchValue);
int curIndex = lastValue + match.Index;
sb.Append(html.Substring(lastValue, curIndex));
sb.AppendFormat(tempUserBlock, p, index++);
lastValue = curIndex + match.Length;
}
}
sb.Append(html.Substring(lastValue));
html = sb.ToString();
以下原始邮件:
这里是原始Java:
private static final String tempUserBlock = "%%%COMPRESS~USER{0}~{1}%%%";
String html = "some html";
int p = 0;
List<String> userBlock = new ArrayList<String>();
Matcher matcher = patternToMatch.matcher(html);
int index = 0;
StringBuffer sb = new StringBuffer();
while (matcher.find())
{
if (matcher.group(0).trim().length() > 0)
{
userBlock.add(matcher.group(0));
matcher.appendReplacement(sb, MessageFormat.format(tempUserBlock, p, index++));
}
}
matcher.appendTail(sb);
html = sb.toString();
到目前为止我的C转换
private const string tempUserBlock = "%%%COMPRESS~USER{0}~{1}%%%";
string html = "some html";
int p = 0;
var userBlock = new ArrayList();
MatchCollection matcher = preservePattern.Matches(html);
int index = 0;
StringBuilder sb = new StringBuilder();
for(var i = 0; i < matcher.Count; ++i){
string match = matcher[i].Groups[0].Value;
if(match.Trim().Length > 0) {
userBlock.Add(match);
// WHAT DO I DO HERE?
sb.Append( string.Format(tempUserBlock, p, index++) );
}
}
// WHAT DO I DO HERE?
matcher.appendTail(sb);
html = sb.toString();
参见上面的评论,我在这里问,“我在这里做什么?”
澄清
上面的Java代码正在执行一些HTML上的字符串替换。它保存最初替换的文本,因为在完成某些空白压缩后,需要稍后重新插入。