0

I have this string:

CN=Salaried_Emplyees,OU=Migration,OU=Groups

and need a regex to replace everything from the beginning of the string up to the first comma only with whatever I want, ie change to:

CN=Anything,OU=Migration,OU=Groups

However every regex I try ends up matching to the last comma rather than stopping after the first one.

An example of what I've tried:

"CN=Salaried_Emplyees,OU=Migration,OU=Groups" -replace "^CN=.*,", "Anything"

ends up as

AnythingOU=Groups

EDIT:

I'd like to modify this further now by not matching the CN= part so it will only match:

Salaried_Emplyees,

not

CN=Salaried_Emplyees,

2 Answers 2

2
"CN=Anything,OU=Migration,OU=Groups" -replace '^(.*?),','YOURTEXT'

replace everything up to first comma (including it), basically you need to use *? for regex to be lazy and not greedy

"CN=Anything,OU=Migration,OU=Groups" -replace '(CN=)(.*?),','$1YOURTEXT,'
Sign up to request clarification or add additional context in comments.

2 Comments

fantastic! it worked. Can you explain how please? as I tried lots of different ways. I think it's he brackets that made the difference
but generally speaking that's not very nice of you to do that @Mucker
0

Just to show a different way,

$string = "CN=Salaried_Emplyees,OU=Migration,OU=Groups"
$string
$Newstring = $string -replace "^[^,]+", "CN=Anything"
$Newstring
  • The ^ anchors at begin
  • the [^,]+ is a negated characcter class matching everything but a comma
  • the + means at least one of the previous.

Sample output

> Q:\Test\2017-03\SO_42543257.ps1
CN=Salaried_Emplyees,OU=Migration,OU=Groups
CN=Anything,OU=Migration,OU=Groups

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.