Splitting string using multiple delimiters Java

戏子无情 提交于 2020-01-06 03:34:32

问题


I would like to split a string using multiple delimiters. Right now I am using this: String delims = "[\\s;.,:'!?()]"; which seems to work fine for those characters, but when I try to add the - character, it yells at me. How can I use all of these characters plus - as delimiters to split my string? Thanks in advance!


回答1:


- has a special meaning in character classes, indicating ranges. (E.g. [0-9] will match any digit.)

However, if you put if you put it either as the first character or the last it will be matched as a literal -.




回答2:


  • inside the character class has a special meaning. It is usually used to select a range of characters like: [a-z] ... In order to match the dash alone ... either keep it in the beginning or the end

I just tried this and it worked

  String regex = "[\\s;.,:'!?()-]";
  String text = "jatin-shah-testing";

  String[] tokens = text.split(regex);
  for(int i = 0; i < tokens.length; i++)
    System.out.println(tokens[i]);


来源:https://stackoverflow.com/questions/15774500/splitting-string-using-multiple-delimiters-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!