MANISH KUMAR CHOUDHARY
MANISH KUMAR CHOUDHARY

Reputation: 3482

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.

Upvotes: 1

Views: 96

Answers (4)

Salman Arshad
Salman Arshad

Reputation: 272136

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.

Upvotes: 1

Xyv
Xyv

Reputation: 739

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

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

http://regexr.com/3blqm

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

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626929

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

Upvotes: 2

NeverHopeless
NeverHopeless

Reputation: 11233

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.

Upvotes: 3

Related Questions