java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0 +

前端 未结 5 1222
旧时难觅i
旧时难觅i 2020-12-15 15:54

I am getting the error when I launch my UI that causes this code to spit the error at me in the title. It works for all of my other operator symbols so I am really not sure

相关标签:
5条回答
  • 2020-12-15 16:24

    Change: String[] split = nums.split(operator);

    To this: String[] split = nums.split("\\" + operator);

    edit: This will only work for standard operators, not the x or X. You'll have to change your String[] operators declaration actually, like the other answer mentioned. Personally though, I'd do some kind of input validation and do a replace() on x or X to be * instead

    0 讨论(0)
  • 2020-12-15 16:24

    the split() method uses regex. the '+' symbol is a special character in regex, so you need to escape it with the backslash symbol ('\'). But you also need to escape the backslash symbol in java, so you need two backslashes, e.g. "\\+"

    0 讨论(0)
  • 2020-12-15 16:34

    There are reserved character in Regex and you should scape these character to achieve what you want. For example, you can't use String.split("+"), you have to use String.split("\\+").

    The correct operators would be:

    String[] operators = new String[] {"-","\\+","/","\\*","x","\\^","X"};
    
    0 讨论(0)
  • 2020-12-15 16:41

    in your case + * and ^ are treated with a special meaning, most often called as Metacharacters. String.split() method takes a regex expression as its argument and return a String array. To avoid treating above as a Metacharacters you need to use these escape sequences in your code "\\+" "\\*" "\\^"

    modify your operator array like this

    private String[] operators = new String[] {"-","\\+","/","\\*","x","\\^","X"};
    

    for more detalis refere these links regex.Pattern and String.split()

    0 讨论(0)
  • 2020-12-15 16:44

    you can use case String.valueOf('+');

    0 讨论(0)
提交回复
热议问题