1

I have been trying to match a Regex query with a string that sometimes contains Regex "power" characters eg. (foo)bar

I am unable to directly effect whether or not these "power" characters are there. I have one solution which is to append a \ to every Regex "power" character but that solution is not ideal and increase the chance of the script missing some entries if I miss any of the "power" characters. e.g:

(($Regex_find_results -replace ')','\)') -replace '(','\(')

So is there a way to have Regex ignore all Regex rules inside part of a Regex query?

Regex with only Powershell code:

$Current_Replace_Regex = "($Regex_find_results)(«){2}[.\- ,\w]+(«){3} Other Matching text"

Regex with example:

$Current_Replace_Regex = "(example (1) here)(«){2}[.\- ,\w]+(«){3} Other Matching text"

Match Example (if brackets are escaped in the above Regex):

example (1) here««abc««« Other Matching text
Adam
  • 21
  • 4
  • 2
    Use `[regex]::Escape('StringToReplace')` to create a regex escaped string that you can use with `-replace`. If you don’t want to use regex, then use `string.Replace('oldstring','newstring')` – – AdminOfThings Mar 02 '20 at 01:55
  • Thanks! Thats exactly what I was looking for. However, I assume that means there is no way to do this inside of the Regex query itself? – Adam Mar 02 '20 at 02:20
  • 1
    I think it is easier to not do what you want. To me it is easier to just build a string that mixes the rules together. `"{0}{1}" -f [regex]::escape('some string'),$regex_stuff` – AdminOfThings Mar 02 '20 at 02:56
  • Adam, no, there is no _in-line_ way to escape _parts_ of a regex for verbatim interpretation; use the approach @AdminOfThings suggests; [this answer](https://stackoverflow.com/a/60068470/45375) contrasts `-replace` with `.Replace()`. – mklement0 Mar 02 '20 at 02:58

0 Answers0