I am trying to name a folder based on a file name, using regex in powershell.
The name looks something like this tester2-2013-14-10.txt
.
With that file name being said, I want to create a folder named tester2
. It will do this for all files in a directory. Basically the regex needs to read up until the first '-', then ignore all other characters after that. It
All regular expressions that I am trying have not worked to do such a things.
Here is the regex I am trying to use (\\w+)\\.txt
.
And here it is when I try and implement it:
Get-ChildItem | Where{$_.Name -match '(\w+)\.txt'} | ForEach-Object{
md $matches[1]}
Along with other variations of this type of thing.
It appears that when I run a file name against this regex, it is using the end of the string. Such as in the case of tester2-2013-14-10.txt
. The folder name that is being created is called 10
instead of Tester2
.
Appreciate the help!
Try following regex
^(\w+)-.*\.txt
Refer to regex101 demo for validation and explanation.
Short Description
^
matches start of the line or string. It will ensure that match should be at the starting of a line.
Hence ^(\\w+)
will match the first word in the file name. Then it has to be followed by -
and any characters until .txt
What's wrong with your regex?
(\\w+)\\.txt
will match a word (\\w+)
immediately followed by .txt
.
Hence you are getting last word instead of the first word.
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.