简体   繁体   English

Java replaceAll仅查找字符串的一部分

[英]Java replaceAll only finding part of string

I am attempting to parse through a file of Java code and change comments that contain a dev's name and it switch the format. 我试图解析Java代码文件并更改包含开发人员名称的注释,并切换格式。 An example of comments are: 评论示例如下:

//Code modified by James on 10/28/2014 for report enhancement Start --- C1
//Code modified by Steven on 10/28/2014 to show report enhancement Start --- C1 

And what I would like them to become: 我希望他们成为:

// Company Name report enhancement Start --- C1
// Company Name show report enhancement Start --- C1

The replaceAll line I made is as follows: 我所做的replaceAll行如下:

String temp = line.replaceAll("//.*([Jj]ames)|([Ss]teven).*(to|for)", "// Company Name");

But the result string that I get is: 但是我得到的结果字符串是:

//Code modified by // Company Name report enhancement End --- C57844

I could just change the replacement string to only have the Company Name, but I don't understand why the regular expression drops the "//Code modified by" at the begin when it is part of the matcher. 我可以只将替换字符串更改为仅包含公司名称,但是我不明白为什么正则表达式在匹配器的一部分开始时会删除“ // Code by by by”。 Explanations on why this is happening and suggestions on what to change my regular expression would be appreciated. 解释为什么会发生这种情况,以及有关更改正则表达式的建议。

The problem is with the parentheses around the dev's names. 问题出在开发人员姓名的括号内。

The pipe ( | ) character is taking the left part //.*([Jj]ames) and ORing it with the right part ([Ss]teven).*(to|for) . 竖线( | )字符取//.*([Jj]ames)的左部分,然后与右部分([Ss]teven).*(to|for) 或运算 Eventually you end up with matching either of the parts. 最终,您最终会匹配任何一个部分。

To solve it, you can adapt the parentheses as follows: 要解决此问题,可以按如下所示修改括号:

String temp = line.replaceAll("//.*([Jj]ames|[Ss]teven).*(to|for)", "// Company Name");

This way the OR pipe will be restricted to match either [Jj]ames or [Ss]teven . 这样,OR管道将被限制为匹配[Jj]ames[Ss]teven

I haven't tested this, but I think you need a reluctant modifier for this to work. 我尚未对此进行测试,但是我认为您需要一个勉强的修饰符才能使其正常工作。

Try: 尝试:

line.replaceAll("//.*?([Jj]ames)|([Ss]teven).*?(to|for)", "// Company Name");

I wrote the following: 我写了以下内容:

public static void main(String[] args){
    String line = "//Code modified by James on 10/28/2014 for report enhancement Start --- C1";
    String temp = line.replaceAll("//.*([Jj]ames)|([Ss]teven).*(to|for)", "// Company Name");
    System.out.println(temp);
}

and got output:// Company Name on 10/28/2014 for report enhancement Start --- C1 so your replace is correct.You must have something else wrong in your code. 并在2014年10月28日获得了输出://公司名称,以进行报表增强开始--- C1,所以您的替换是正确的。您的代码中必须还有其他错误。

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

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