简体   繁体   English

Eclipse Regex搜索和替换交换位置

[英]Eclipse Regex Search and Replace Swap places

I have code like this all over my class: 我在全班都有这样的代码:

if (src.getTYPERECORD().getACT().equalsIgnoreCase("B"))

Now it can crash if the getters return null, and for the team's Best Practices, I was asked to convert it into: 现在,如果吸气剂返回null,它可能会崩溃,并且对于团队的最佳实践,我被要求将其转换为:

if ("B".equalsIgnoreCase(src.getTYPERECORD().getACT()))

I have come up with the following regex for search for the easier case of where I already had the value assigned to variable like act.equalsIgnoreCase("B"): 我想出了以下正则表达式来搜索更简单的情况,在这种情况下,我已经将值赋给了act.equalsIgnoreCase(“ B”)这样的变量:

(\w*).equalsIgnoreCase\("(\w*)"\)

Replace with: 用。。。来代替:

"\2".equalsIgnoreCase(\1)

Which works except for the cases mentioned above, AND this: 除上述情况外,哪种方法有效,并且:

tos.substring(1,1).equalsIgnoreCase("A")

Could you please help come up with the search and replace regex to catch the two examples mentioned above? 您能否帮忙提出搜索并替换正则表达式以捕获上述两个示例? It would need to account for situations where the opening IF bracket is adjacent, and where there is a space like if ( src.... or if (src.... 它需要考虑到中频IF括号相邻且存在if(src ....或if(src ....

Thanks! 谢谢!

Just changing like this should work : 只是像这样进行更改应该起作用:

\b([\S]*?).equalsIgnoreCase\("(\w*)"\)

Take a look at the example here at rubular . 看一看在rubular的示例。

Java 8's Optional to the rescue! Java 8的Optional

if (Optional.ofNullable(src).map(Source::getTYPERECORD)
    .map(TypeRecord::getACT).orElse("").equalsIgnoreCase("B"))

If anything is null along the chain, including src itself, the orElse() fires and the test will be false. 如果沿链的任何内容(包括src本身orElse()为null, orElse()触发orElse() ,并且测试将为false。 Otherwise, the test works as expected. 否则,测试将按预期进行。

This does the job: 这样就可以了:

Search: if\s*\(\s*(src.*)\.equalsIgnoreCase\((.*?)\)
Replace: if (\2.equalsIgnoreCase(\1)

Tested in Eclipse. 在Eclipse中测试。

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

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