我需要能够提取两个标签之间的字符串例如:"00002“从"morenonxmldata<tag1>0002</tag1>morenonxmldata
”
我使用的是C#和.NET 3.5。
发布于 2009-11-12 03:59:19
不需要正则表达式的解决方案:
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);
}
发布于 2009-11-12 03:58:16
Regex regex = new Regex("<tag1>(.*)</tag1>");
var v = regex.Match("morenonxmldata<tag1>0002</tag1>morenonxmldata");
string s = v.Groups[1].ToString();
或者(如注释中所述)匹配最小子集:
Regex regex = new Regex("<tag1>(.*?)</tag1>");
Regex
类位于System.Text.RegularExpressions
命名空间中。
发布于 2009-11-12 04:07:58
一种使用惰性匹配和反向引用的Regex
方法:
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);
}
https://stackoverflow.com/questions/1717611
复制相似问题