简体   繁体   中英

Replacing all strings int java source code

I am trying to replace every declared String that is inside of a Java formatted source code (using java itself). A source code to remove the strings from may look like this (>...< indicates what should be matched):

package a.b;

import b.a.*;

@SomeAnnotation(>"abc"<)
public class XY extends YZ {

    String s = >"Hello \"World\""<;

    public static void main(String[] args) {
        System.out.println(>"Hello World"<);
    }
}

Imagine this all stored in one string, possibly without the newlines. I now need a regex that can find all of these. I am having trouble with the escaped quotation marks inside of the strings. My best bet is ".*[^\]" .

It does not matter whether it will detect these inside of comments, as long as it does not excede the comment.

If you read in the source code in another java application with a BufferedLineReader and check every line you could maybe use the following regex:

(?:\>\")(([\w\s]*)(\\"(?!\<)))*(?:\"\<)

However you would want to escape all of the backslashes when used inside the java replace method.

eg:

lineAsString.replace((?:\\>\\")(([\\w\\s]*)(\\\\"(?!\\<)))*(?:\\"\\<),"youReplacementString");

Maybe additional escape sequences might be necessary. Also, you might want to add further special chars to be allowed inside the string beside \w and \s .

I suggest to paste that regex into a regex checker like https://regex101.com/ and your sample code for more explanations.

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