0

I am trying to replace a string that is not surrounded by brackets. When I am using string.Replace(), it replaces all values (inside and outside of brackets). What should i use to replace values that is only outside of brackets?

Original string: "Example string: `REPLACEME` (`REPLACEME`)"

Required string: "Example string: `REPLACEMENT` (`REPLACEME`)"

P.S. I am not trying to replace first value from string, important here to replace value OUT OF BRACKETS

Adam Cooper
  • 8,077
  • 2
  • 33
  • 51
  • For now i collected all indexes of brackets and i can check if variable is inside it or not, but i still doesn't know how to make correct replacing – Strange Potato Dec 31 '19 at 03:17
  • Does this answer your question? [Replace first occurrence of pattern in a string](https://stackoverflow.com/questions/8809354/replace-first-occurrence-of-pattern-in-a-string) – Jawad Dec 31 '19 at 03:18
  • @Jawad I am not trying to replace first value from string, important here to replace value OUT OF BRACKETS. It can be first, second, XXX, doesnt matters what position is – Strange Potato Dec 31 '19 at 03:20
  • https://stackoverflow.com/questions/42526951/regex-to-match-text-but-not-if-contained-in-brackets – Strange Potato Dec 31 '19 at 03:27
  • You can always use the leading spaces in your favor: `Replace(" 'REPLACEME' ", " 'REPLACEMENT' ")` – Guilherme Dec 31 '19 at 04:05

1 Answers1

1

You could use following Regex with Negavtive LookAhead and LookBehind

(?<!\()\`\bREPLACEME\b\`(?![\w\s]*[\)])

For example,

var str = @"Example string: `REPLACEME` (`REPLACEME`)";
var result = Regex.Replace(str,@"(?<!\()\`\bREPLACEME\b\`(?![\w\s]*[\)])","`REPLACEMENT`");

Where

(?<!\() : Negative Look Behind that matches the Character (

(?![\)]): Negative Lookahead that matches the Character )

Regex Demo

Anu Viswan
  • 17,797
  • 2
  • 22
  • 51
  • Thanks for answer. but i have one issue - it will match if there are something between Example: (random things here`REPLACEMENT` random things here) – Strange Potato Dec 31 '19 at 04:07
  • 1
    @StrangePotato You should update your question with a **worst case** example string to describe your problem better - something like "foo( foo ) foofoo foo (foo )" should evaluate to "bar( foo ) barbar bar (foo )" – Sir Rufo Dec 31 '19 at 04:47