Search code examples
regexsublimetext3pcre

Search / and replace it with ; in xml tag with sublime text 3


I am working on an .xml file with this tag

<Categories><![CDATA[Test/Test1-Test2-Test3|Test4/Test5-Test6|Test7/Test8]]></Categories>

and I am trying to replace / with ; by using regular expressions in Sublime Text 3.

The output should be

<Categories><![CDATA[Test;Test1-Test2-Test3|Test4;Test5-Test6|Test7;Test8]]></Categories>

When I use this (<Categories>\S+)\/(.+</Categories>) it matches all the line and of course if I use this \/ it matches all / everywhere inside the .xml file.

Could you please help?


Solution

  • For you example string, you could make use of a \G to assert the position at the end of the previous match and use \K to forget what has already been matched and then match a forward slash.

    In the replacement use a ;

    Use a positive lookahead to assert what is on the right is ]]></Categories>

    (?:<Categories><!\[CDATA\[|\G(?!^))[^/]*\K/(?=[^][]*]]></Categories>)
    

    Explanation

    • (?: Non capturing group
      • <Categories><!\[CDATA\[ Match <Categories><![CDATA[
      • | Or
      • \G(?!^) Assert the position at the end of the previous match, not at the start
    • ) Close non capturing group
    • [^/]* Match 0+ times not / using a negated character class
    • \K/ Forget what was matched, then match /
    • (?= Positive lookahead, assert what is on the right is
      • [^][]*]]></Categories> Match 0+ times not [ or ], then match ]]></Categories>
    • ) Close positive lookahead

    Regex demo