简体   繁体   English

intellij中的正则表达式编译

[英]Regex compilation in intellij

I am trying to do: 我正在尝试做:

uri=uri.replaceFirst("{}",param.toString());

I'm supposed to use regex in place of {} but that should not be a compilation problem because method signature takes String and {} is a perfectly valid string. 我应该使用正则表达式代替{}但这不应该是编译问题,因为方法签名采用String,而{}是完全有效的字符串。 Below is replaceFirst() : 下面是replaceFirst()

public String replaceFirst(String regex, String replacement) 

Help me understand how is this a compilation error. 帮助我了解这是一个编译错误。

IntellijIDEA 2018.1 IntellijIDEA 2018.1

The first parameter is expected to be a valid regex. 第一个参数应该是有效的正则表达式。 Because there are metacharacters, you must escape: 因为存在元字符,所以您必须转义:

uri=uri.replaceFirst("\\{\\}",param.toString());

IntelliJ does inspection that allows it to report such errors. IntelliJ进行检查 ,使其能够报告此类错误。 This is an IDE feature. 这是一个IDE功能。 Compiling this code with javac wouldn't cause it to fail. 使用javac编译此代码不会导致它失败。

You can disable inspection (alt+enter, details on the page linked to above): 您可以禁用检查(alt + enter,上面链接到的页面上的详细信息):

在此处输入图片说明

{} is a special regex character which represents the range operator so you have to escape it before using it {}是一个特殊的正则表达式字符,它表示范围运算符,因此在使用前必须对其进行转义

// normal use
    "".replaceFirst("a{1,2}","");

As shown, {} is recognised as range to match minimum and maximum occurrences of a 如图所示, {}是公认的范围相匹配的最小和最大的出现a

so while using regex you have to provide some character/word along with minimum and maximum value with range operator {} (otherwise it can cause regex engine to crash or behave unexpectedly so compiler is being proactive here) 因此,在使用正则表达式时,您必须提供一些字符/单词以及范围运算符{}最小值和最大值(否则可能会导致regex引擎崩溃或行为异常,因此此处的编译器处于主动状态)

solution : escape it using \\\\ 解决方案:使用\\\\对其进行转义

uri = uri.replaceFirst("\\{\\}",param.toString());

This is NOT a compilation error that you receive. 这不是您收到的编译错误。 It's an inspection from IntelliJ, even though it's underlined in red. 这是来自IntelliJ的检查,即使它带有红色下划线。

在此处输入图片说明

You may disable the inspection by going into your settings 您可以通过进入设置来禁用检查

在此处输入图片说明

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

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