简体   繁体   English

替换所有字符串 int java 源代码

[英]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).我正在尝试替换 Java 格式的源代码中的每个声明的字符串(使用 java 本身)。 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:如果您使用 BufferedLineReader 阅读另一个 java 应用程序的源代码并检查每一行,您可能会使用以下正则表达式:

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

However you would want to escape all of the backslashes when used inside the java replace method.但是,在 java 替换方法中使用时,您可能希望转义所有反斜杠。

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 .此外,您可能希望在\w\s旁边的字符串中添加更多特殊字符。

I suggest to paste that regex into a regex checker like https://regex101.com/ and your sample code for more explanations.我建议将该正则表达式粘贴到像https://regex101.com/这样的正则表达式检查器和您的示例代码中以获得更多解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM