简体   繁体   中英

Excluding specific regex match from general regex match

I have been trying various combos and cannot seem to get the regex I need for a C# .Net application.

I have a text document that can contain the following :

{{{3456764345345}}} yadda yadda yadda {{{xyz}}} 

{{{3456764345345}}} can have any alpha-numeric value in it and will be different per document, while {{{xyz}} will always be {{{xyz}}} initially.

So, you could have the following documents:

{{{3456764345345}}} yadda yadda yadda {{{xyz}}} 
{{{45435555}}} yadda yadda yadda {{{xyz}}} 
{{{54727r475t76777a4}}} yadda yadda yadda {{{xyz}}} 

I want to replace both {{{3456764345345}}} and {{{xyz}}} with different values. The problem is when I try to replace {{{3456764345345}}} it replaces itself and {{{xyz}}} making it so I am unable to replace the second value.

I am currently using:

{{{.*?}}} 

as my expression. This works to find the first but it also includes the second.

I need an expression that allows me to find the first value but exclude the {{{xyz}}} value.

Thanks in advance.

You could replace {{{xyz}}} substrings first then go for other triple-braced substrings or:

str = Regex.Replace(str, @"{{{(?!xyz\b)\w+}}}", "O_o");
str = Regex.Replace(str, @"{{{xyz}}}", "o_O");

Breaking {{{(?!xyz\\b)\\w+}}} down:

  • {{{ Match {{{ literally
    • (?!xyz\\b) Next characters shouldn't be xyz
    • \\w+ Match word characters, at least one
  • }}} Match }}} literally

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