简体   繁体   中英

string replace but only if not contained within 2 other strings

Imagine I have a string like:

xxxstrvvv string xxxstringvvv str I am string for testing.

I want to find and replace all instances of str with xxxstrvvv that are not already contained in a xxxvvv .

so the result would be:

xxxstrvvv xxxstrvvving xxxstringvvv xxxstrvvv I am xxxstrvvving for testing

Anyone know an easy way to do this?

Edit: I want to add another situation to clarify.

xxxabcstrefgvvv

it should NOT replace this because the str is contained in xxxvvv

I suggest using regular expression with negative looking ahead and behind :

string source = "xxxstrvvv string xxxstringvvv str I am string for testing.";

string result = Regex.Replace(source, @"(?<!xxx)str(?!vvv)", "xxxstrvvv");

Edit: Same method, but a bit different pattern for the edited question:

string result = Regex.Replace(
    source, 
  @"(?<!xxx[a-zA-Z]*)str(?![a-zA-Z]*vvv)", "xxxstrvvv");

Outcomes:

  1. source = "xxxstrvvv string xxxstringvvv str I am string for testing." :

    xxxstrvvv xxxstrvvving xxxstringvvv xxxstrvvv I am xxxstrvvving for testing.

  2. source = "xxxabcstrefgvvv" :

    xxxabcstrefgvvv

Ok, I agreed with the answer of Dmitry Bychenko about Regular Expressions. But, if your request is limited to the requirement on your answer we can use this code:

string val = "xxxstrvvv string xxxstringvvv str I am string for testing."; val = val.Replace("xxxstringvvv", "str"); val = val.Replace("str","xxxstringvvv");

I'd go with the regex, but if you want to use replaces, this would work, if you don't have "xxxxxxstrvvvvvv" in your initial string and want to keep them that way:

string findString = "str";
string addBefore = "xxx";
string addAfter = "xxx";
string myString = "xxxstrvvv string xxxstringvvv str I am string for testing.";

myString = myString.Replace(findString, addBefore+findString+addAfter);
myString = myString.Replace(addBefore+addBefore+findString+addAfter+addAfter, addBefore+findString+addAfter);

Yes; it is ugly. I just basically do that in Notepad++ all the time with ctrl-H .

I have written a script in Python. I think you would be able to convert it to C#.

one_line = 'xxxstrvvv string xxxstringvvv str I am string for testing'
final_str = ""
arry_len = one_line.split(" ")

for ch in arry_len:
    if 'str' in ch:
      if not 'xxxstrvvv' in ch:
        ch = ch.replace("str","xxxstrvvv")
    final_str = final_str + " " + ch

print final_str

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