Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 查找两个已知值之间的字符串_C#_.net_Regex - Fatal编程技术网

C# 查找两个已知值之间的字符串

C# 查找两个已知值之间的字符串,c#,.net,regex,C#,.net,Regex,我需要能够提取两个标记之间的字符串,例如“morenxmldata0002morenonxmldata”中的“00002” 我正在使用C#和.NET3.5。Regex Regex=newregex((*); Regex regex = new Regex("<tag1>(.*)</tag1>"); var v = regex.Match("morenonxmldata<tag1>0002</tag1>morenonxmldata");

我需要能够提取两个标记之间的字符串,例如“
morenxmldata0002morenonxmldata
”中的“00002”

我正在使用C#和.NET3.5。

Regex Regex=newregex((*);
  Regex regex = new Regex("<tag1>(.*)</tag1>");
  var v = regex.Match("morenonxmldata<tag1>0002</tag1>morenonxmldata");
  string s = v.Groups[1].ToString();
var v=regex.Match(“morenonxmldata0002morenonxmldata”); 字符串s=v.Groups[1].ToString();
或(如注释中所述)匹配最小子集:

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

Regex
类位于
System.Text.RegularExpressions
命名空间中。

不需要正则表达式的解决方案:

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);
}
string ExtractString(字符串s,字符串标记){
//您应该检查实际代码中的错误,为简洁起见省略了这些错误
var startTag=“”;
int startIndex=s.IndexOf(startTag)+startTag.Length;
int-endIndex=s.IndexOf(“,startIndex);
返回s.Substring(startIndex,endIndex-startIndex);
}

A
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);
}
foreach(Regex.Matches中的匹配(
“morenonxmldata0002morenonxmldataabcasd”,
@"]+)>(.*?)"))
{
Console.WriteLine(“{0}={1}”,
match.Groups[1]。值,
匹配。组[2]。值);
}

为了将来的参考,我在中找到了这个代码片段,如果您需要搜索不同的“标记”,它工作得非常好

    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;
    }
公共静态字符串[]GetStringInBeween(字符串strBegin,
字符串强度,字符串strSource,
bool includeBegin,bool includeEnd)
{
字符串[]结果={“”“”};
int iIndexOfBegin=strSource.IndexOf(strBegin);
如果(iIndexOfBegin!=-1)
{
//如果需要,包括开始字符串
如果(包括开始)
iIndexOfBegin-=标准长度;
strSource=strSource.Substring(iIndexOfBegin
+标准长度);
int iEnd=strSource.IndexOf(strengd);
如果(iEnd!=-1)
{
//如果需要,包括结束字符串
如果(包括结束)
iEnd+=强度长度;
结果[0]=strSource.Substring(0,iEnd);
//超越这一部分
if(iEnd+强度长度
两个更精细的字符串之间的公共字符串(字符串行、字符串分隔符first、字符串分隔符last)
{
string[]splitterFirst=新字符串[]{delimiterFirst};
string[]splitterLast=新字符串[]{delimiterLast};
字符串[]拆分;
字符串缓冲区;
splitRes=line.Split(splitterFirst,100000,System.StringSplitOptions.removeMptyEntries);
buildBuffer=splitRes[1];
splitRes=buildBuffer.Split(splitterLast,100000,System.StringSplitOptions.RemoveEmptyEntries);
返回splitRes[0];
}
私有无效按钮1\u单击(对象发送者,事件参数e)
{
string manyLines=“已接收:由isp2.ihc.ru与本地(exim 4.77)从exim发送\nX失败的收件人:rmnokixm@gmail.com\nFrom:邮件递送系统”;
MessageBox.Show(在两个更精细的(多行,“X-Failed-Recipients:”,“\n”)之间);
}

我在数据之前和之后剥离

 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();
         }
     }
 }
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.Text.RegularExpressions;
命名空间testApp
{
班级计划
{
静态void Main(字符串[]参数)
{
string tempString=“morenxmldata0002morenonxmldata”;
tempString=Regex.Replace(tempString,[\\s\\s]*,“”);//删除所有前导数据
tempString=Regex.Replace(tempString,[\\s\\s]*,“”);//删除所有尾随数据
Console.WriteLine(tempString);
Console.ReadLine();
}
}
}

不带正则表达式,带有一些必备的值检查

    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);
    }
publicstaticstringextractstring(stringsoapmessage,stringtag)
{
if(string.IsNullOrEmpty(soapMessage))
返回消息;
var startTag=“”;
int startIndex=soapMessage.IndexOf(startTag);
startIndex=startIndex==-1?0:startIndex+startTag.Length;
int-endIndex=soapMessage.IndexOf(“,startIndex);
endIndex=endIndex>soapMessage.Length | | endIndex==-1?soapMessage.Length:endIndex;
返回soapMessage.Substring(startIndex,endIndex-startIndex);
}

在两个已知值之间提取内容对以后也很有用。那么为什么不为它创建一个扩展方法呢。以下是我所做的,简短而简单

  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;
    }

不使用正则表达式获取单个/多个值

// For Single
var value = inputString.Split("<tag1>", '</tag1>')[1];

// For Multiple
var values = inputString.Split("<tag1>", '</tag1>').Where((_, index) => index % 2 != 0);
//对于单个
var值=inputString.Split(“,”)[1];
//多次
var值=inputString.Split(“,”)。其中(((uu,index)=>索引%2!=0);

这很危险!在这个strig上:“aabbbcccdddeee”它将返回“bbbcccddd”@Aaron:通过将
(.*)
更改为
(.*)
,使用非贪婪匹配-这将防止@Kugel提到的错误匹配。当我这样做时,它将返回and以及中间的字符串?!那个按钮点击代码和什么有什么关系?或者神奇的100000数字?如果它们是同一标签的倍数,如何才能获得价值?这是一个没有正则表达式的惊人单行程序,我一直在努力解决这个问题。现在我不用用了。非常感谢。
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;
// For Single
var value = inputString.Split("<tag1>", '</tag1>')[1];

// For Multiple
var values = inputString.Split("<tag1>", '</tag1>').Where((_, index) => index % 2 != 0);