Split string at hyphen characters too

前端 未结 3 1781
故里飘歌
故里飘歌 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]
    

提交回复
热议问题