简体   繁体   中英

How to write regular expression to get the substring from the string using regular expression in c#?

I have following string

string s=@"\Users\Public\Roaming\Intel\Wireless\Settings"; 

I want output string like

string output="Wireless";

Sub-string what I want should be after "Intel\\" and it should ends with the first "\\" after "Intel\\" before string Intel and after Intel the string may be different. I have achieved it using string.substring() but I want to get it using regular expression ? what regular expression should I write to get that string.

For a regex solution you may use:

(?<=intel\\)([^\\]+?)[\\$]

Demo

Notice the i flag.

BTW, Split is much simpler and faster solution than regexes. Regex is associated with patterns of string. For a static/fixed string structure, it is a wise solution to manipulate it with string functions.

With regex, it will look like

var txt = @"\Users\Public\Roaming\Intel\Wireless\Settings";
var res = Regex.Match(txt, @"Intel\\([^\\]+)", RegexOptions.IgnoreCase).Groups[1].Value;

But usually, you should use string methods with such requirements. Here is a demo code (without error checking):

var strt = txt.IndexOf("Intel\\") + 6;   // 6 is the length of "Intel\"
var end = txt.IndexOf("\\", strt + 1);   // Look for the next "\"
var res2 = txt.Substring(strt, end - strt); // Get the substring

See IDEONE demo

You could also use this if you want everything AFTER the intel/

/(?:intel\\)((\w+\\?)+)/gi

http://regexr.com/3blqm

You would need the $1 outcome. Note that $1 will be empty or none existent if the string does not contain Intel/ or anything after it.

Why not use Path.GetDirectoryName and Path.GetFileName for this:

string s = @"\Users\Public\Roaming\Intel\Wireless\Settings";
string output = Path.GetFileName(Path.GetDirectoryName(s));
Debug.Assert(output == "Wireless");

It is possible to iterate over directory components until you find the word Intel and return the next component.

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