RaviLobo
RaviLobo

Reputation: 508

PowerShell string replace using RegEx

This is rather a RegEx question than PS one. Here it goes:

I have a text file with data like below.

ABC Corp, x567 
xyz Corp, y567 
pqr Corp, m567 
ghysds ,inc, x567 
TRWsdsdsds ,org, y567 
TYUds ,ing, m567

How can I remove the first comma from line 4-6? (These lines have 2 commas. I need only the second one.) My plan is to insert this data into a table with 2 columns.

Thank you.

Upvotes: 0

Views: 879

Answers (3)

mjolinor
mjolinor

Reputation: 68243

Here's mine:

$text = 
(@'
ABC Corp, x567
xyz Corp, y567 
pqr Corp, m567 
ghysds ,inc, x567 
TRWsdsdsds ,org, y567 
TYUds ,ing, m567
'@).split("`n")

$text -replace '(.+?),(.+?),(.+)','$1$2,$3'

ABC Corp, x567
xyz Corp, y567 
pqr Corp, m567 
ghysds inc, x567 
TRWsdsdsds org, y567 
TYUds ing, m567

Upvotes: 1

user189198
user189198

Reputation:

You don't really need regular expressions for this, although it would work.

$StringList = @('abd,asdc,asdc', 'asdc,awegwe,aweg', 'asdfasdf,asdaweg');

foreach ($String in $StringList) {
    if ($String -match '.*,.*,') {
        $String.Remove($String.IndexOf(','), 1);
    }
    else {
        $String;
    }
}

Upvotes: 0

kabb
kabb

Reputation: 2502

You have to use look ahead to check to see if there is a second comma on the line.

,(?=.*,)

Use this to replace whatever it matches with an empty string. This will get rid of the first comma of lines that have two commas in them.

Upvotes: 2

Related Questions