2

Can a Regular Expression find the text within a pattern and allow me to replace the non found text with PowerShell? So I have this issue where many AssemblyInfo.CS are different across 100+ projects:

  • AssemblyCopyright("Copyright © My Company Full Name Ltd 2016")]
  • AssemblyCopyright("Copyright © 2016")]
  • AssemblyCopyright("© 2016")]

Is it possible for it to find AssemblyCopyright("")] and then allow me to insert my own text to where the other text was, even if the text is different within the brackets?

3 Answers 3

1

You can use this regex:

AssemblyCopyright\(".*"\)\]

And replace with the string of your choice:

AssemblyCopyright("The string of your choice")]
Sign up to request clarification or add additional context in comments.

Comments

0

Powershell regex might be disturbing because of multiple way to deal with escape characters :

So as you nested your string beetween simple quote :

  • Groups can be marked with bracket or not : (.n) or .n
  • Double quotes can be considered as standard characters
  • Brackets can be considered as standard characters

If you nested your string beetween double quote, the double quote inside the string must be escape with standard powershell escape character : `"

So all following examples return the same result

$pattern = 'AssemblyCopyright("what ever in there")]'

# standard regex
$pattern -replace 'AssemblyCopyright\(\"(.*)\"\)\]', 'AssemblyCopyright("new pattern")]'
# no quote escape
$pattern -replace 'AssemblyCopyright\("(.*)"\)\]', 'AssemblyCopyright("new pattern")]'
# no brackets escape
$pattern -replace 'AssemblyCopyright\("(.*)"\)]', 'AssemblyCopyright("new pattern")]'
# no parenthesis to define group
$pattern -replace 'AssemblyCopyright\(".*"\)]', 'AssemblyCopyright("new pattern")]'
# double quote instead of simple quote
$pattern -replace "AssemblyCopyright\(`".*`"\)]", "AssemblyCopyright(`"new pattern`")]"

Comments

0

An example with more advanced regular-expression techniques:

> 'AssemblyCopyright("foo bar")]' -replace '(?<=AssemblyCopyright\(")[^"]*', 'bar'
AssemblyCopyright("bar")]
  • (?<=AssemblyCopyright\(") is a lookbehind assertion that matches the specified subexpression, but doesn't make it part of the match (what is captured and, in this case, replaced).

  • Since the lookbehind assertion found everything up to and including the opening " of the attribute, all we need is to match up to but excluding the next " ([^"]*) to fully match only the contents of the double-quoted string (the attribute value).

  • Thus, we only need to specify the attribute value as the replacement string (sans quoting).

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.