简体   繁体   中英

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.

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.

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

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM