Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to remove what ever comes in front of "\" using powershell

wanted one help, wanted a regex to eliminate a "\" and what ever come before it,

Input should be "vmvalidate\administrator" 
and the output should be just "administrator"
like image 928
PowerShell Avatar asked May 22 '13 14:05

PowerShell


3 Answers

$result = $subject -creplace '^[^\\]*\\', ''

removes any non-backslash characters at the start of the string, followed by a backslash:

Explanation:

^      # Start of string
[^\\]* # Match zero or more non-backslash characters
\\     # Match a backslash

This means that if there is more than one backslash in the string, only the first one (and the text leading up to it) will be removed. If you want to remove everything until the last backslash, use

$result = $subject -creplace '(?s)^.*\\', ''
like image 143
Tim Pietzcker Avatar answered Nov 20 '22 01:11

Tim Pietzcker


No need to use regex, try the split method:

$string.Split('\')[-1]
like image 35
Shay Levy Avatar answered Nov 20 '22 01:11

Shay Levy


"vmvalidate\administrator" -replace "^.*?\\"
  • ^ - from the begin of string
  • .* - any amount of any chars
  • ? - lazy mode of quantifier
  • \ - "backslash" using escape character ""

All together it means "Replace all characters from the begin of string until backslash"

like image 2
Yuriy Kim Avatar answered Nov 20 '22 01:11

Yuriy Kim