rad_
rad_

Reputation: 301

Use regex to get value from varying strings

I am trying to figure out how to setup a regex to find a specific part of a string off of varying pieces of data.

IE, I have a PC log with the filename of TTEST7-17.txt or a filename of TTEST7-17.28-11-2018.txt

Basically, I just want the value "TTEST7-17" which would be the PC name.

But it has to pull that value no matter if the filename is TTEST7-17.txt or TTEST7-17.28-11-2018.txt

Each PC name and date is different, so it can't just match to one PC name and pull the string that way. It has to somehow determine IF it is formatted like TTEST7-17 or TTEST7-17.28.11.2018.txt and THEN either get rid of .txt or .28.11.2018.txt, no matter what the PC name is.

Upvotes: 0

Views: 26

Answers (1)

boxdog
boxdog

Reputation: 8432

You can use the split() method. For example:

"TTEST7-17.28.11.2018.txt".Split('.')[0]

"TTEST7-17.txt".Split('.')[0]

Both of these give output of TTEST7-17.

Of course, if the name is in a variable, you can still use this method:

$fileName = "TTEST7-17.28.11.2018.txt"

$fileName.Split('.')[0]

Upvotes: 1

Related Questions