小编典典

更换支架时例外

java

嘿,我想用下划线替换随机字母(仅第一个字母)。为此,我使用以下行:

String newSubstring=substring.replaceFirst(randomLetter,"_");

除非有括号“(”或“)”,否则效果很好。然后我得到以下异常:

06-14 15:29:48.090: E/AndroidRuntime(12466): FATAL EXCEPTION: main
06-14 15:29:48.090: E/AndroidRuntime(12466): Process: com.clozegenerator, PID: 12466
06-14 15:29:48.090: E/AndroidRuntime(12466): java.util.regex.PatternSyntaxException:     Incorrectly nested parentheses in regexp pattern near index 1:
06-14 15:29:48.090: E/AndroidRuntime(12466): )
06-14 15:29:48.090: E/AndroidRuntime(12466):  ^
06-14 15:29:48.090: E/AndroidRuntime(12466):    at java.util.regex.Pattern.compileImpl(Native Method)
06-14 15:29:48.090: E/AndroidRuntime(12466):    at java.util.regex.Pattern.compile(Pattern.java:411)
06-14 15:29:48.090: E/AndroidRuntime(12466):    at java.util.regex.Pattern.<init>(Pattern.java:394)
06-14 15:29:48.090: E/AndroidRuntime(12466):    at java.util.regex.Pattern.compile(Pattern.java:381)
06-14 15:29:48.090: E/AndroidRuntime(12466):    at java.lang.String.replaceFirst(String.java:1804)
06-14 15:29:48.090: E/AndroidRuntime(12466):    at com.clozegenerator.MainActivity.generateCloze(MainActivity.java:138)
06-14 15:29:48.090: E/AndroidRuntime(12466):    at com.clozegenerator.MainActivity.onClick(MainActivity.java:113)
06-14 15:29:48.090: E/AndroidRuntime(12466):    at android.view.View.performClick(View.java:4480)
06-14 15:29:48.090: E/AndroidRuntime(12466):    at android.view.View$PerformClick.run(View.java:18673)
06-14 15:29:48.090: E/AndroidRuntime(12466):    at android.os.Handler.handleCallback(Handler.java:733)
06-14 15:29:48.090: E/AndroidRuntime(12466):    at android.os.Handler.dispatchMessage(Handler.java:95)
06-14 15:29:48.090: E/AndroidRuntime(12466):    at android.os.Looper.loop(Looper.java:157)
06-14 15:29:48.090: E/AndroidRuntime(12466):    at android.app.ActivityThread.main(ActivityThread.java:5872)
06-14 15:29:48.090: E/AndroidRuntime(12466):    at java.lang.reflect.Method.invokeNative(Native Method)
06-14 15:29:48.090: E/AndroidRuntime(12466):    at java.lang.reflect.Method.invoke(Method.java:515)
06-14 15:29:48.090: E/AndroidRuntime(12466):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1069)
06-14 15:29:48.090: E/AndroidRuntime(12466):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:885)
06-14 15:29:48.090: E/AndroidRuntime(12466):    at dalvik.system.NativeStart.main(Native Method)

有什么想法可以解决吗?


阅读 217

收藏
2020-11-30

共1个答案

小编典典

replaceFirst用途正则表达式作为第一个参数,在正则表达式()特殊(他们打开和关闭为例),所以你需要使用实例来逃避他们\\(或他们周围有\\Q
\\E代表的报价。

但是为了避免手动转义,您可以使用Pattern.quote类似

String newSubstring=substring.replaceFirst(Pattern.quote(randomLetter),"_");
2020-11-30