Split string at hyphen characters too

前端 未结 3 1782
故里飘歌
故里飘歌 2021-01-21 18:28

The line below splits my string on (.), (,), (:) and newline (\\n) characters.

String[] textPhrases = text.sp         


        
相关标签:
3条回答
  • 2021-01-21 18:38

    I need to split on hyphen characters too, but this does not work...What am I missing or doing wrong?

    To answer your question first off on what's wrong in this picture, you have forward slashes inside of your character class around your hyphen. Instead you should be using the escape sequence character (\\)

    [.,:/-/\\n]
        ^^^ Remove these and replace with the escape sequence character (\\-)
    

    Within a character class [], you can place a hyphen (-) as the first or last character. You may also escape it ([.,:\\-\n]) to add the hyphen in order to be matched.

    String s  = "hey,hi.foo:bar\nbaz-quz";
    String[] parts = s.split("[.,:\n-]");
    System.out.println(Arrays.toString(parts));
    

    Output

    [hey, hi, foo, bar, baz, quz]
    
    0 讨论(0)
  • 2021-01-21 18:43

    You have to use:

    String[] textPhrases = text.split("[.,:\\-\\n]");
    
    0 讨论(0)
  • 2021-01-21 18:57

    This is regex. A hyphen has a special meaning inside a character class. You need to place the hyphen as the first or last item in the class:

    [-.,:\n]
    
    0 讨论(0)
提交回复
热议问题