简体   繁体   中英

c# Extract String By Regex

i use Regex extract string text here ..

+CMGR: "REC UNREAD","MSG","","2013/11/04 14:17:43+28" 0E2A0E270E310E2A0E140E350E040E230E310E1A00200E220E340E190E140E350E150E490E2D0E190E230E310E1A0E040E230E310E1A0E170E380E010E460E040E19

i need select text

"0E2A0E270E310E2A0E140E350E040E230E310E1A00200E220E340E190E140E350E150E490E2D0E190E230E310E1A0E040E230E310E1A0E170E380E010E460E040E19"

i use code :

        string strRegex = @"\b+CMGR: w+\n(\w+)\b";
        RegexOptions myRegexOptions = RegexOptions.Multiline;
        Regex myRegex = new Regex(strRegex, myRegexOptions);
        string strTargetString = @"+CMGR: ""REC UNREAD"",""MSG"","""",""2013/11/04 13:52:18+28""" + "\r\n" + @"0E2A0E270E310E2A0E140E350E040E230E310E1A00200E220E340E190E140E350E150E490E2D0E190E230E310E1A0E040E230E310E1A0E170E380E010E460E040E197";

        foreach (Match myMatch in myRegex.Matches(strTargetString))
        {
            if (myMatch.Success)
            {
               return myRegex.Split(strTargetString);
            }
        }

is can't extract it..

Thank you

To find last line you may use \\w+$ pattern:

string strRegex = @"\w+$";    
Regex myRegex = new Regex(strRegex);
string strTargetString = @"+CMGR: ""REC UNREAD"",""MSG"","""",""2013/11/04 13:52:18+28""" + "\r\n" + @"0E2A0E270E310E2A0E140E350E040E230E310E1A00200E220E340E190E140E350E150E490E2D0E190E230E310E1A0E040E230E310E1A0E170E380E010E460E040E197";
return myRegex.Match(strTargetString);

. But the simplest way is to split string into lines and select the second one:

strTargetString.Split('\n')[1]

Your code will work with this patter: "^+.+\\s"

void Main()
{
    string strRegex = @"^\+.+\s";
        RegexOptions myRegexOptions = RegexOptions.Multiline;
        Regex myRegex = new Regex(strRegex, myRegexOptions);
        string strTargetString = @"+CMGR: ""REC UNREAD"",""MSG"","""",""2013/11/04 13:52:18+28""" + "\r\n" + @"0E2A0E270E310E2A0E140E350E040E230E310E1A00200E220E340E190E140E350E150E490E2D0E190E230E310E1A0E040E230E310E1A0E170E380E010E460E040E197";

        foreach (Match myMatch in myRegex.Matches(strTargetString))
        {
            if (myMatch.Success)
            {
               Console.WriteLine(myRegex.Split(strTargetString));
            }
        }
}

output

0E2A0E270E310E2A0E140E350E040E230E310E1A00200E220E340E190E140E350E150E490E2D0E190E230E310E1A0E040E230E310E1A0E170E380E010E460E040E197

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM