java.util.regex.PatternSyntaxException:索引附近的正则表达式模式中的语法错误

时间:2013-09-03 10:30:30

标签: java android regex

分成以下代码

String s = "12+12";
String[] sr = s.split("+");

我在logcat中收到此错误

09-03 15:57:22.489: E/AndroidRuntime(22029): FATAL EXCEPTION: main
09-03 15:57:22.489: E/AndroidRuntime(22029): java.util.regex.PatternSyntaxException: Syntax error in regexp pattern near index 1:
09-03 15:57:22.489: E/AndroidRuntime(22029): +
09-03 15:57:22.489: E/AndroidRuntime(22029):  ^
09-03 15:57:22.489: E/AndroidRuntime(22029):    at java.util.regex.Pattern.compileImpl(Native Method)
09-03 15:57:22.489: E/AndroidRuntime(22029):    at java.util.regex.Pattern.compile(Pattern.java:407)
09-03 15:57:22.489: E/AndroidRuntime(22029):    at java.util.regex.Pattern.<init>(Pattern.java:390)
09-03 15:57:22.489: E/AndroidRuntime(22029):    at java.util.regex.Pattern.compile(Pattern.java:381)
09-03 15:57:22.489: E/AndroidRuntime(22029):    at java.lang.String.split(String.java:1832)
09-03 15:57:22.489: E/AndroidRuntime(22029):    at java.lang.String.split(String.java:1813)
09-03 15:57:22.489: E/AndroidRuntime(22029):    at net.telivo.fiestacancun.ui.calllog.CallLogDetailsFragment$1.onClick(CallLogDetailsFragment.java:171)
    09-03 15:57:22.489: E/AndroidRuntime(22029):    at android.view.View.performClick(View.java:4240)
09-03 15:57:22.489: E/AndroidRuntime(22029):    at android.view.View$PerformClick.run(View.java:17721)
09-03 15:57:22.489: E/AndroidRuntime(22029):    at android.os.Handler.handleCallback(Handler.java:730)
09-03 15:57:22.489: E/AndroidRuntime(22029):    at android.os.Handler.dispatchMessage(Handler.java:92)
09-03 15:57:22.489: E/AndroidRuntime(22029):    at android.os.Looper.loop(Looper.java:137)
09-03 15:57:22.489: E/AndroidRuntime(22029):    at android.app.ActivityThread.main(ActivityThread.java:5103)
09-03 15:57:22.489: E/AndroidRuntime(22029):    at java.lang.reflect.Method.invokeNative(Native Method)
09-03 15:57:22.489: E/AndroidRuntime(22029):    at java.lang.reflect.Method.invoke(Method.java:525)
09-03 15:57:22.489: E/AndroidRuntime(22029):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
09-03 15:57:22.489: E/AndroidRuntime(22029):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-03 15:57:22.489: E/AndroidRuntime(22029):    at dalvik.system.NativeStart.main(Native Method)

4 个答案:

答案 0 :(得分:40)

String#split接受正则表达式

如果您不想逃离special char +,可以使用Pattern#quote

  

返回指定String的文字模式String


String sr[] = s.split(Pattern.quote("+"));

+现在将被视为常规字符,而不是元字符。

答案 1 :(得分:9)

您应该转义+字符。

String s = "12+12";
String[] sr = s.split("\\+");

转义正则表达式通常由\完成,但在Java \中表示为\\

答案 2 :(得分:4)

+应该被转义,因为+用于代表其中一个quantifiers

应为s.split("\\+");

答案 3 :(得分:2)

由于+是一个元字符且在regex中具有特殊含义,您必须转义该元字符

String s = "12+12";
String[] sr = s.split("\\+");

oracle docs on the same