PowerShell file paths - c#

I run the command (Get-Location), and it returns the current location of a file.
Example: c:\folder1\folder2\folder3\XXX\folder4\folder5
Firstly, from the above, I want to get the value of XXX and let it equal to a variable. How can I do this?
Secondly, I want to get the value of c:\folder1\folder2\folder3\XXX\folder4\ and let it equal to a variable. How can I do this?
I have used the placeholders folder1, folder2, etc. for illustration. These are dynamic.

To answer your second question first: to get the parent to the full path, use Split-Path:
$var = Split-Path -parent "c:\folder1\folder2\folder3\XXX\folder4\folder5"
For your other question, this function will split all the elements of your path and return them into an array:
function Split-Paths($pth)
{
while($pth)
{
Split-Path -leaf $pth
$pth = Split-Path -parent $pth
}
}
You can then grab the 5th element like this:
$xxx = (Split-Paths "c:\folder1\folder2\folder3\XXX\folder4\folder5")[-5]
Note that the function returns the elements in "reverse" order, so you use a negative index to index from the end of the array.

Some of these answers are pretty close, but everyone is forgetting their shell-fu.
$FirstAnswer = (Get-Item ..\..).Name
$SecondAnswer = (Get-Item ..).FullName

To get the path into a variable, you can do something like this:
$a = (Get-Location).Path
Then, if you want to set the value of the 'XXX' part of your path to a variable, you can use the split() function:
$x = $a.split('\')[4]

You could do this with a regular expression:
PS> $path = 'c:\folder1\folder2\folder3\XXX\folder4\folder5'
PS> $path -match 'c:\\([^\\]+)\\([^\\]+)\\([^\\]+)\\([^\\]+)'
True
PS> $matches
Name Value
---- -----
4 XXX
3 folder3
2 folder2
1 folder1
0 c:\folder1\folder2\folder3\XXX

You can use regular expressions:
$rawtext = "If it interests you, my e-mail address is tobias#powershell.com."
# Simple pattern recognition:
$rawtext -match "your regular expression"
*True*
# Reading data matching the pattern from raw text:
$matches
$matches returns the result.
For more information, check Chapter 13. Text and Regular Expressions (requires registration).

Related

Regex in C# acting weird

I've encountered a problem while working with regex in C#. Namely, the debugger shows correct(IMO) results but when I try to print the results in my application, they are different(and wrong). Code below:
Match match2 = Regex.Match("048 A Dream Within A Dream (satur) (123|433) K48", "(.*)(\\((.)*?\\))\\s\\((.)*?\\)\\s.*");
string nick = match2.Groups[1].Value;
string name = match2.Groups[0].Value;
Console.WriteLine("nick - '{0}', name - '{1}'", nick, name);
Expected results show up in the debugger, as in following screenshot:
Console shows different(wrong) results:
nick - '048 A Dream Within A Dream ', name - '048 A Dream Within A
Dream (satur) (123|433) K48'
How do I fix it? I want the results to be shown exactly as in debugger.
You're missing the fact that Groups[0] is always meant to represent the whole match. The first capturing group is in Groups[1]. You want:
string nick = match2.Groups[2].Value;
string name = match2.Groups[1].Value;
The reason it's showing what you expected in the debugger is that you're looking at the implementation detail of a field within GroupCollection; when it's asked for a group by number, it returns the match if the requested number is 0, or offsets the number by 1 otherwise.
From the documentation for GroupCollection:
If the match is successful, the first element in the collection contains the Group object that corresponds to the entire match. Each subsequent element represents a captured group, if the regular expression includes capturing groups.
You are looking into _groups field, but it's not exactly what is returned as Groups property:
Change your code to use Groups[1] and Groups[2]:
string nick = match2.Groups[2].Value;
string name = match2.Groups[1].Value;

Regex for replacing dashes with underscores in directory names and not the filenames

The string example is:
/my/test-is/for-this/to/work-right.txt
should be:
/my/test_is/for_this/to/work-right.txt
Anyone want to flex their Regex-Fu muscles?
No, not really. It's much better to use Path.GetDirectoryName and friends:
var s = "/my/test-is/for-this/to/work-right.txt";
var result = Path.Combine(
Path.GetDirectoryName(s).Replace("-", "_"),
Path.GetFileName(s)
);
If your path uses / as the directory separator, you are running on Windows and you don't want it to be replaced by \ you can simply undo the replacement afterwards:
// What I 'm really doing here is showing that these constants exist;
// read the manual to see what you can expect from them.
result = result.Replace(
Path.DirectorySeparatorChar,
Path.AltDirectorySeparatorChar
);

Regex to extract function-name, & it's parameters

I am building an application where the user can specify an expression for some fields. The expression shall contain functions too. I need to evaluate these expressions and display final value in report.
I had an expression to extract function-name & it's paramters. Previously, the function parameters were decimal values. But now, the parameters can also be expression.
For ex,
Round( 1 * (1+ 1 /100) % (2 -1), 0)
Function-name : Round
Parameter1 : 1 * (1+ 1 /100) % (2 -1)
Parameter2 : 0
Previous Regex:
string pattern2 = #"([a-zA-Z]{1,})[[:blank:]]{0,}\(([^\(\)]{0,})\)";
This regex does not help me anymore to find expression-parameters.
Can someone help me with the right regex to extract function-name & parameters? I am implement all or most of the functions supported by Math class.
The program is built in c#
Thanks in advance for the help.
"^\s*(\w+)\s*\((.*)\)"
group(1) is function name
split group(2) with "," you get para list.
updated
since I don't have Windows system (.Net either), I test it with python. nested function is not a problem. if we add "^\s*" at the beginning of the expression:
import re
s="Round(floor(1300 + 0.234 - 1.765), 1)"
m=re.match("^\s*(\w+)\s*\((.*)\)",s)
m.group(1)
Output: 'Round'
m.group(2)
Output: 'floor(1300 + 0.234 - 1.765), 1'
you can split if you like:
m.group(2).split(',')[0]
Out: 'floor(1300 + 0.234 - 1.765)'
m.group(2).split(',')[1]
Out: ' 1'
well, if your function nesting is like f(a(b,c(x,y)),foo, m(j,k(n,o(i,u))) ), my code won't work.
You could try writing a parser, instead of using regular expressions.
The Irony library is (in my opinion) extremely easy to use, and in the examples there's something very similar to what you are trying to do.
From the post Regex for matching Functions and Capturing their Arguments, you can extract your function using Kent regex and use this code to extract parameters form the last group :
string extractArgsRegex = #"(?:[^,()]+((?:\((?>[^()]+|\((?<open>)|\)(?<-open>))*\)))*)+";
var ArgsList = Regex.Matches(m.Groups[m.Groups.Count - 1].Value, extractArgsRegex);

c# string analysis

I have a string for example like " :)text :)text:) :-) word :-( " i need append it in textbox(or somewhere else), with condition:
Instead of ':)' ,':-(', etc. need to call function which enter specific symbol
I thinck exists solution with Finite-state machine, but how implement it don't know. Waiting for advises.
update: " :)text :)text:) :-) word :-( " => when we meet ':)' wec all functions Smile(":)") and it display image on the textbox
update: i like idea with delegates and Regex.Replace. Can i when meet ':)' send to the delegate parameter ':)' and when meet ':(' other parameter.
update: Found solution with converting to char and comparing every symbol to ':)' if is equal call smile(':)')
You can use Regex.Replace with delegate where you can process matched input or you can simply use string.Replace method.
Updated:
you can do something like this:
string text = "aaa :) bbb :( ccc";
string replaced = Regex.Replace(text, #":\)|:\(", match => match.Value == ":)" ? "case1" : "case2");
replaced variable will have "aaa case1 bbb case2 ccc" value after execution.
It seems that you want to replace portions of the string with those symbols, right? No need to build that yourself, just use string.Replace. Something like this:
string text = " :)text :)text:) :-) word :-( ";
text = text.Replace(":)", "☺").Replace(":(", "☹"); // similar for others
textbox.Text += text;
Note that this is not the most efficient code ever produced, but if this is for something like a chat program, you'll probably never know the difference.
You could just create a dictionary with these specific characters as the key and pull the value.

Extracting Data from a String Using Regular Expressions

I need some help extracting the following bits of information using regular expressions.
Here is my input string "C:\Yes"
******** Missing character at start of string and in between but not at the end =
a weird superscript looking L.***
I need to extract "C:\" into one string and "Yes" into another.
Thanks In Advance.
I wouldn't bother with regular expressions for that. Too much work, and I'd be too likely to screw it up.
var x = #"C:\Yes";
var root = Path.GetPathRoot(x); // => #"C:\"
var file = Path.GetFileName(x); // => "Yes"
The following regular expression returns C:\ in the first capture group and the rest in the second:
^(\w:\\)(.*)$
This is looking for: a full string (^…$) starting with a letter (\w, although [a-z] would probably more accurate for Windows drive letters), followed by :\. All the rest (.*) is captured in the second group.
Notice that this won’t work with UNC paths. If you’re working with paths, your best bet is not to use strings and regular expressions but rather the API found in System.IO. The classes found there already offer the functionality that you want.
Regex r = new Regex("([A-Z]:\\)([A-Za-z]+)");
Match m = r.Match(#"C:\");
string val1 = m.Groups[0];
string val2 = m.Groups[1];

Categories