SOSidb
SOSidb

Reputation: 574

Using regexes in PowerShell to remove text from a string

I need to replace (remove) multiple possibilities of text in a string and I'm trying to do it all in one line (instead of having a bunch of if this do that stuff). For example, I have a number of users with job titles, all at different levels (Manager 1, Manager 2, etc.). Some of them end with numbers but some of them end with II, III, IV, etc. (roman numerals). I'm using the following to remove the numbers (yes, in an array):

$_.CSVJobTitle = ((Get-Culture).TextInfo.ToTitleCase($objCSV."Job Title".ToLower())) -Replace " \d+$"

And that works great. It removes the numbers from all of the Job Titles. Because I am doing title case also, when the Job Title has III, I end up with Iii (using proper case). But, when I try to add more to the above:

$_.CSVJobTitle = ((Get-Culture).TextInfo.ToTitleCase($objCSV."Job Title".ToLower())) -Replace " \d+$","ii$","iii$","iv$"

I get the following error message:

The -ireplace operator only permits 2 elements on the right-hand side, not 4

So I've been researching how to make this work and I keep reading about regex being the answer, and I'm sure that this is a simple answer, but I can't seem to understand how to make regex work in this situation. I've read and tried so much on regexes and just can't get it and need help. Is there some way to use the above command and remove (replace with nothing) the items that I am trying to remove? Or is there a hard limit and I need to figure out something else?

Upvotes: 0

Views: 324

Answers (1)

mjolinor
mjolinor

Reputation: 68273

How about using a character class?

$_.CSVJobTitle = ((Get-Culture).TextInfo.ToTitleCase($objCSV."Job Title".ToLower())) -Replace '\s[0-9ivx]+$'

Or, with a some alternation thrown in:

-Replace '\s(?:\d+|[ivx]+)$'

Upvotes: 3

Related Questions