variable usar una que propiedades programacion manejo invertida funciones como cadenas cadena asigna c# .net regex

c# - usar - Encuentre una cadena entre 2 valores conocidos



propiedades de string c# (9)

Necesito poder extraer una cadena entre 2 etiquetas, por ejemplo: "00002" de " morenonxmldata<tag1>0002</tag1>morenonxmldata "

Estoy usando C # y .NET 3.5.


La extracción de contenidos entre dos valores conocidos también puede ser útil para más adelante. Entonces, ¿por qué no crear un método de extensión para ello? Esto es lo que hago, Corto y simple ...

public static string GetBetween(this string content, string startString, string endString) { int Start=0, End=0; if (content.Contains(startString) && content.Contains(endString)) { Start = content.IndexOf(startString, 0) + startString.Length; End = content.IndexOf(endString, Start); return content.Substring(Start, End - Start); } else return string.Empty; }


Para referencia futura, encontré este fragmento de código en http://www.mycsharpcorner.com/Post.aspx?postID=15 Si necesita buscar diferentes "etiquetas", funciona muy bien.

public static string[] GetStringInBetween(string strBegin, string strEnd, string strSource, bool includeBegin, bool includeEnd) { string[] result ={ "", "" }; int iIndexOfBegin = strSource.IndexOf(strBegin); if (iIndexOfBegin != -1) { // include the Begin string if desired if (includeBegin) iIndexOfBegin -= strBegin.Length; strSource = strSource.Substring(iIndexOfBegin + strBegin.Length); int iEnd = strSource.IndexOf(strEnd); if (iEnd != -1) { // include the End string if desired if (includeEnd) iEnd += strEnd.Length; result[0] = strSource.Substring(0, iEnd); // advance beyond this segment if (iEnd + strEnd.Length < strSource.Length) result[1] = strSource.Substring(iEnd + strEnd.Length); } } else // stay where we are result[1] = strSource; return result; }


Sin RegEx, con alguna comprobación de valor imprescindible

public static string ExtractString(string soapMessage, string tag) { if (string.IsNullOrEmpty(soapMessage)) return soapMessage; var startTag = "<" + tag + ">"; int startIndex = soapMessage.IndexOf(startTag); startIndex = startIndex == -1 ? 0 : startIndex + startTag.Length; int endIndex = soapMessage.IndexOf("</" + tag + ">", startIndex); endIndex = endIndex > soapMessage.Length || endIndex == -1 ? soapMessage.Length : endIndex; return soapMessage.Substring(startIndex, endIndex - startIndex); }


Tira antes y después de los datos.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Text.RegularExpressions; namespace testApp { class Program { static void Main(string[] args) { string tempString = "morenonxmldata<tag1>0002</tag1>morenonxmldata"; tempString = Regex.Replace(tempString, "[//s//S]*<tag1>", "");//removes all leading data tempString = Regex.Replace(tempString, "</tag1>[//s//S]*", "");//removes all trailing data Console.WriteLine(tempString); Console.ReadLine(); } } }


Un enfoque Regex que usa la concordancia Regex y la retrospectiva:

foreach (Match match in Regex.Matches( "morenonxmldata<tag1>0002</tag1>morenonxmldata<tag2>abc</tag2>asd", @"<([^>]+)>(.*?)<//1>")) { Console.WriteLine("{0}={1}", match.Groups[1].Value, match.Groups[2].Value); }


Una solución libre de RegEx :

string ExtractString(string s, string tag) { // You should check for errors in real-world code, omitted for brevity var startTag = "<" + tag + ">"; int startIndex = s.IndexOf(startTag) + startTag.Length; int endIndex = s.IndexOf("</" + tag + ">", startIndex); return s.Substring(startIndex, endIndex - startIndex); }


public string between2finer(string line, string delimiterFirst, string delimiterLast) { string[] splitterFirst = new string[] { delimiterFirst }; string[] splitterLast = new string[] { delimiterLast }; string[] splitRes; string buildBuffer; splitRes = line.Split(splitterFirst, 100000, System.StringSplitOptions.RemoveEmptyEntries); buildBuffer = splitRes[1]; splitRes = buildBuffer.Split(splitterLast, 100000, System.StringSplitOptions.RemoveEmptyEntries); return splitRes[0]; } private void button1_Click(object sender, EventArgs e) { string manyLines = "Received: from exim by isp2.ihc.ru with local (Exim 4.77) /nX-Failed-Recipients: [email protected]/nFrom: Mail Delivery System <[email protected]>"; MessageBox.Show(between2finer(manyLines, "X-Failed-Recipients: ", "/n")); }


Regex regex = new Regex("<tag1>(.*)</tag1>"); var v = regex.Match("morenonxmldata<tag1>0002</tag1>morenonxmldata"); string s = v.Groups[1].ToString();

O (como se menciona en los comentarios) para que coincida con el subconjunto mínimo:

Regex regex = new Regex("<tag1>(.*?)</tag1>");

Regex clase Regex está en el System.Text.RegularExpressions nombres System.Text.RegularExpressions .


string input = "Exemple of value between two string FirstString text I want to keep SecondString end of my string"; var match = Regex.Match(input, @"FirstString (.+?) SecondString ").Groups[1].Value;