2010-09-24 7 views
5

ACTUALIZACIÓNCuál es el C# expresión regular equivalente a la de Java y appendReplacement appendTail

Esto es lo que ocurrió. Todavía no lo he probado porque es parte de un código mucho más grande que aún necesita ser portado.

¿Puedes ver algo que esté fuera de lugar?

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(); 

post original ABAJO:

Aquí está el original de 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(); 

Y mi C# conversión hasta el momento

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(); 

Ver comentario arriba, donde pregunto, "¿QUÉ HAGO AQUÍ?"

Aclaración
El código Java anterior se realiza el reemplazo cadena en algo de HTML. Guarda el texto originalmente reemplazado porque necesita volver a insertarse más tarde después de que se complete la compresión del espacio en blanco.

+1

¿Cuál es el problema? – erickson

+2

¿Puede definir mejor el problema, como, cuál es el resultado esperado y cuál es el resultado que está obteniendo? – CodingGorilla

+5

Supongo que son las partes marcadas con '// ¿QUÉ HAGO AQUÍ?' – jrummell

Respuesta

5

No hay necesidad de reproducir la funcionalidad de Java appendReplacement/appendTail; .NET tiene algo mejor: MatchEvaluator. Compruébelo usted mismo:

string holder = "Element {0} = {1}"; 
string s0 = "111 222 XYZ"; 
ArrayList arr = new ArrayList(); 

string s1 = Regex.Replace(s0, @"\d+", 
    m => string.Format(holder, arr.Add(m.Value), m.Value) 
); 

Console.WriteLine(s1); 
foreach (string s in arr) 
{ 
    Console.WriteLine(s); 
} 

de salida:

Element 0 = 111 Element 1 = 222 XYZ 
111 
222 

Hay varias formas de implementar la MatchEvaluator, todo minuciosamente discutido en this article. Esta (expresiones lambda) es de lejos la más genial.

+1

Lo comprobaré en la mañana. +1 para la programación basada en "frialdad". –

+1

Excelente. Esto funcionó muy bien. Gracias. –

2

No estoy familiarizado con las clases de expresiones regulares de Java, pero esta es mi C# interpretación de lo que creo que hace su código:

private const string tempUserBlock = "%%%COMPRESS~USER{0}~{1}%%%"; 
string html = "some html"; 
int p = 0; 
var userBlock = new List<string>(); 

MatchCollection matcher = preservePattern.Matches(html); 
StringBuilder sb = new StringBuilder(); 
int last = 0; 
foreach (Match m in matcher) 
{ 
    string match = m.Groups[0].Value; 
    if(match.Trim().Length > 0) { 
     userBlock.Add(match); 
     sb.Append(html.Substring(last, m.Index - last)); 
     sb.Append(m.Result(string.Format(tempUserBlock, p, index++))); 
    } 
    last = m.Index + m.Length; 
} 
sb.Append(html.Substring(last)); 
html = sb.ToString(); 
+1

impresionante, ¡eso es casi exactamente lo que se me ocurrió! Coloca el m.Index + m.Length en el lugar correcto. Gracias. Te dejaré saber cómo funciona en un momento. –

+1

Funciona perfectamente. ¡Gracias! –

Cuestiones relacionadas