简体   繁体   中英

How do I parse a string using C# and regular expressions?

How do I convert the string:

"Microsoft Windows XP Professional x64 Edition|C:\\\\WINDOWS|\\\\Device\\\\Harddisk4\\\\Partition1"

to

"Microsoft Windows XP Professional x64 Edition"

...using regular expressions?

I want to cut out all after | symbol. Is it easy to realise it via Regex.Replace ? Where could I found syntax description for Regex.Replace patterns?

You don't need a Regex for that. You can use substring:

var text = @"Microsoft Windows XP Professional x64 Edition|C:\WINDOWS|\Device\Harddisk4\Partition1";
text = text.Substring(0,text.IndexOf("|"));
string str = @"Microsoft Windows XP Professional x64 Edition|C:\WINDOWS|\Device\Harddisk4\Partition1";
string str2 = str.Split('|')[0];

str2 = "Microsoft Windows XP Professional x64 Edition"

If you're determined to use a regular expression:

Regex p = new Regex(@"([^|]*)|");
string s = @"Microsoft Windows XP Professional x64 Edition|C:\\WINDOWS|\\Device\\Harddisk4\\Partition1";
s = p.Match(s).Value;

使用String.Split(),它产生一个String [],然后选择零元素。

string GetOSType(string data)
{
      return data.Split(Convert.ToChar("|"))[0];
}

this is assuming the string is ALWAYS going to split. Probably to be sure you would want to wrap a try - catch block around this function.

如果您仍然想了解有关正则表达式的更多信息,这里有一个不错的备忘单和一个简单的在线正则表达式生成器工具 ,可以帮助您入门。

A simple solution may be to use:

    string szOrig = "Microsoft Windows XP Professional x64 Edition|C:\\WINDOWS|\\Device\\Harddisk4\\Partition1";
    string[] separator = new string[] { "|" };
    string[] szTemp = szOrig.Split(separator, StringSplitOptions.RemoveEmptyEntries);
    string szRequired = szTemp[0];

May not be the best way, but works.

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