How to remove all text after specific text with rule for each line?



  • For example I have a text file:

    String s = New String("abc")  //Converted abce //BC3031
    DoSomething(s)                //Converted xyza //BC3012
    int b,c,d
    int a = 12                    //Converted defd //BC3063
    DoSomething(a)                //Converted xyzds //BC3113
    

    I want to remove all text after “//Converted xxxx” at all lines so that the content will be:

    String s = New String("abc")  //Converted abce
    DoSomething(s)                //Converted xyza
    int b,c,d
    int a = 12                    //Converted defd
    DoSomething(a)                //Converted xyzds
    

    Please help me!



  • @lionelanh97 said in How to remove all text after specific text with rule for each line?:

    I want to remove all text after “//Converted xxxx”

    Hello, welcome to the NPP forum.

    As your example is showing a capital letter for “Converted” I have used that exactly as provided.

    So my regular expression (regex) is as follows (Replace function under Search menu):
    Find What:(?-i)//Converted.+(?= //)\K.+
    Replace With: “nothing in this field” (empty field)
    Make sure search mode is set to “regular expression” and have “wrap around” ticked. The “Find What” field is in red characters, you can select them and copy and this will prevent any possible mistyping.

    To give some background on the expression.
    (?-i) means perform a case sensitive search, so “converted” is NOT equal to “Converted”.
    //Converted.+ looks for the characters “//Converted” specifically, then followed by any number of characters (.+), limited by the next step.
    (?= //) is a forward lookup, so it allows the earch engine to stop when the " //" (note space before /) are spotted. Note that as it’s a lookup, these 3 characters are not actually consumed or used at this point.
    \K allows the search engine to drop all characters the regex has thus far consumed (selected). It leaves the pointer immediately before the space which is before the “//”.
    .+ allows selecting ALL characters up to the end of line, not caring what sort of character they are.

    As the replace field is empty this means the characters selected are therefore replaced with nothing and thus deleted.

    I hope this helps. If not then please provide further examples showing where it does not work.

    Terry



  • @Terry-R This is exactly what I want :D Thank you very much!



  • Hello, @lionelanh97, @terry-r and All,

    @terry-r, I don’t think that the look-ahead structure, (?= //) is, even, mandatory !

    This regex S/R should be enough :

    SEARCH (?-si)//Converted.+\K //.+

    REPLACE Leave EMPTY

    As it searches the greatest range of chars .+ between the string //Converted and the string ' //', without the quotes !

    Best Regards,

    guy038


Log in to reply