Remove all values in a string before a backslash

529 Views Asked by At

I have this string

AttendanceList
XXXXXX
US\abraham
EU\sarah
US\gerber

when i try to use -replace it replaces all characters inserted in square bracket (including the first line AttendanceList)

$attendance_new = $attendance -replace "[EU\\]", "" -replace"[US\\], ""
echo $attendance_new

AttndancLit
XXXXXX
abraham
arah
grbr

i was hoping to get this sample output (and possibly concatenate a string "_IN" after all values)

AttendanceList
XXXXXX
abraham_IN
sarah_IN
gerber_IN

I'm new to regex and still trying to figure out the regex code for special characters

1

There are 1 best solutions below

1
Wiktor Stribiżew On

You can use

$attendance_new = $attendance -replace '(?m)^(?:US|EU)\\(.*)', '$1_IN'

See this demo (.NET regex demo here). Details:

  • (?m) - multiline option enabling ^ to match start of any line position
  • ^ - line start
  • (?:US|EU) - EU or US
  • \\ - a \ char
  • (.*) - Group 1: any zero or more chars other than a line feed char (note you might need to replace it with ([^\r\n]*) if you start getting weird results)